自定义控件文字居中
2016-11-08 10:17
204 查看
绘制文字的x,y坐标是baseline左端点的坐标,原来一直理解为了文字的左上角,今天亲测才发现,
文字的x坐标号计算:(控件宽度-文字宽度)/2
文字的y坐标计算:控件高度/2+距离baseline的那段距离(-(decent+ascent)/2)
android绘制文字时以baseline为y轴0坐标线,向上为负,向下为正,所以文字的一半正好是(decent+asecnt)/2,
文字要居中,文字的横向中心线必然与控件的横向中心线重合,而中心线的距离baseline的距离便是(decent+ascent)/2
这个值是负数,所以(控件高度/2)加上它的时候要取它的相反数。
class fontText extends View { Paint accentPaint,baselinePaint,decentPaint,textPaint; float x=60,y=60; public fontText(Context context) { super(context); initPaint(); } public fontText(Context context, AttributeSet attrs) { super(context, attrs); initPaint(); } public fontText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initPaint(); } private void initPaint(){ accentPaint=new Paint(); accentPaint.setColor(Color.BLUE); baselinePaint=new Paint(); baselinePaint.setColor(Color.BLACK); decentPaint=new Paint(); decentPaint.setColor(Color.RED); textPaint=new Paint(); textPaint.setColor(Color.BLACK); textPaint.setTextSize(20); textPaint.setAntiAlias(true); } @Override protected void onDraw(Canvas canvas) { Paint.FontMetrics metrics=textPaint.getFontMetrics(); float ascent= metrics.ascent; float decent=metrics.descent; String text="hguqpwm睡觉啊"; float width=textPaint.measureText(text); y=getMeasuredHeight()/2-(decent+ascent)/2; x=(getMeasuredWidth()-width)/2; canvas.drawText(text,x,y,textPaint); canvas.drawLine(x, y + ascent, x + width, y + ascent, accentPaint); canvas.drawLine(x, y + decent, x + width, y + decent, decentPaint); canvas.drawLine(x,y,x+width,y,textPaint); textPaint.setTextSize(40); canvas.drawLine(0, getMeasuredHeight() / 2, getMeasuredWidth(), getMeasuredHeight() / 2, textPaint); canvas.drawLine(getMeasuredWidth()/2,0,getMeasuredWidth()/2,getMeasuredHeight(),textPaint); }
相关文章推荐
- Android 自定义控件文字的居中绘制
- Android自定义控件TextView---之实现drawableLeft图片和文字一起居中
- 自定义控件使用DrawableLeft/Right图片和文字同时居中
- Android自定义控件之自定义TextView,实现drawableLeft可以和文字一起居中
- 自定义控件使用DrawableLeft/Right图片和文字同时居中
- 自定义控件时绘制文字居中
- css下拉框ie8下面文字居中
- 关于文字垂直居中
- 多行文字垂直居中
- 垂直居中一张图片和多行文字在固定的盒子内
- 浏览器兼容CSS代码:按钮文字垂直居中(input button text vertical align)
- 大小不固定的图片、多行文字的水平垂直居中
- css 设置input的文字居中
- 自定义控件之绘图篇(二):路径及文字
- 自定义控件三部曲之绘图篇(十九)——LinearGradient与闪动文字效果
- android使用zxing扫描界面全是白色以及更改显示文字屏幕居中
- table表格在设置文字垂直居中后,在表格显示相同排列的数据(比如:testtesttesttsttesttesstestse很多的test)时此表格不能换行
- div+css使多行文字垂直居中?
- Web中Input文字垂直居中的办法
- iPhone开发--UITextField中的文字左对齐,垂直高度居中