自定义TextView显示偏移问题

来源:互联网 发布:玲珑醉梦网络剧 编辑:程序博客网 时间:2024/05/21 17:36

自定义TextView显示偏移问题


先上最终要实现的效果图好了:
这里写图片描述

下面上代码:`public class MyTextView extends TextView {
private String titleText;
private int titleColor;
private int titleSize;

private Rect mBound;private Paint mPaint;public MyTextView(Context context) {    this(context,null);}public MyTextView(Context context,AttributeSet attrs){    this(context,attrs,0);}public MyTextView(Context context,AttributeSet attrs,int defStyle){    super(context,attrs,defStyle);    TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyTextView, defStyle, 0);    int n=ta.getIndexCount();//得到属性个数    for(int i=0;i<n;i++) {        int attr = ta.getIndex(i);//属性对应的下标        switch (attr) {            case R.styleable.MyTextView_titleText:                titleText = ta.getString(attr);                break;            case R.styleable.MyTextView_titleColor:                titleColor=ta.getColor(attr, Color.BLACK);                break;            case R.styleable.MyTextView_titleSize:                // 默认设置为16sp,TypeValue也可以把sp转化为px                titleSize = ta.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(                        TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));                break;        }    }    ta.recycle();    mPaint = new Paint();    mPaint.setTextSize(titleSize);    mBound = new Rect();    mPaint.getTextBounds(titleText,0,titleText.length(),mBound);}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {    super.onMeasure(widthMeasureSpec, heightMeasureSpec);}@Overrideprotected void onDraw(Canvas canvas) {    super.onDraw(canvas);    mPaint.setColor(Color.YELLOW);    canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);    mPaint.setColor(titleColor);    canvas.drawText(titleText,0,0,mPaint);}

}


下面放上面代码运行的效果图:这里写图片描述
是不是很奇怪,明明设置的距离top和left都是0,为什么显示不正常,关键就在这句代码:canvas.drawText(titleText,0,0,mPaint);
其实这里设置的相对MyTextView的top和left的距离并不是以包裹着文字内容的mBond为标准的,而是文字本身就有一根BaseLine作为和MyTextView对齐标准,如图:
这里写图片描述
看到了吧, canvas.drawText(titleText,0,0,mPaint);画出文字的时候并不是以图中r为标准的,而是以BaseLine为标准,所以如果上面两个参数都为零的话,就是只能显现出BaseLine一下的文字内容,如果想要正常显示,就必须将r.top这部分的内容下移,而此时的r.top的值一定是个负值,所以 canvas.drawText(titleText,0,-mBond.top,mPaint);


这样调整之后便可以正常显示了

0 0
原创粉丝点击