自定义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
- 自定义TextView显示偏移问题
- textview 光标向下偏移问题
- 自定义返回按钮偏移问题
- android自定义view解决textview显示排版的问题
- 自定义TextView解决超长文字显示的问题
- 关于自定义dialog中textview的显示的问题
- 自定义TextView实现内容的旋转和偏移
- TextView显示行数问题
- 自定义TextView显示指定行数
- 自定义Textview显示自动换行
- 百度地图自定义icon,定位偏移问题
- iOS11导航栏自定义按钮偏移问题
- iOS11导航栏自定义按钮偏移问题
- android drawText 显示向上偏移问题。
- 关于WdatePicker显示位置偏移的问题
- 解决TextView排版不齐问题----自定义TextVIew
- android TextView setSingleLinexia显示问题
- TextView显示不全问题分析
- 上古神器--awk
- ConcurrentHashMap
- python小项目1
- 一款功能强大的设备调试、接口调试工具
- const、static关键字
- 自定义TextView显示偏移问题
- 判断并将矩阵转化为严格对角占优矩阵
- 第三方cocoaPods管理工具的安装步骤
- Android控件架构
- day02
- 类初始化列表
- 轻松搞定Linux端口转发
- 心情无聊透底
- Go语言核心之美 3.6-template模版