android 自定义控件时,往往需要在控件上方加上相应的字体,在网上看了一些答案发现很多人还是通过获取计算图形的绝对坐标,然后通过一些计算方法得到中心坐标来绘制字体,那么如果直接用绝对坐标在图形上画的话,一旦屏幕尺寸变化或者字体发生变化,那么字体将不再居中,有什么方法可以让字体无论图形如何变换还可以在字体中间呢?
答案是使用Paint自带的方法setTextAlign();该方法可以设置字体的显示位置,方法要求传入Align参数,该参数属性有LEFT,RIGHT,CENTER三种,分别可以设置字体位于左边,右边,和中间,而中间正是我们需要的。
下面是简短的代码:
public IconView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.IconView);
text = typedArray.getString(R.styleable.IconView_text);
textSize = typedArray.getDimension(R.styleable.IconView_textSize,20);
typedArray.recycle();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextSize(textSize);
mPaint.setTextAlign(Paint.Align.CENTER);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
canvas.drawRect(0,0,width,height,mPaint);
mPaint.setColor(Color.GREEN);
canvas.drawText(text,width/2,height/2,mPaint);
}
以下为效果图: