您的位置:首页 > 移动开发 > Android开发

Android 自定义View中drawText位置注意事项小记

2016-07-01 11:13 477 查看
自定义view中难免会用到文字。一般做法都是直接drawtext,把里面才参数写上就完事儿了。只要难点在于位置的计算和大小的匹配。我们在attr中设置了自定义属性后。在继承view的类中用
TypedArray ta = context.obtainStyledAttributes(attrs,
R.styleable.xxxx);

获取到之后。在根据里面的属性进行获取。

这些随便都能百度到就不说了。

在设置文字的size和位置的时候要注意

要先设置Paint.setTextSize(),在定义或者设置位置。因为Paint.setTextSize()会影响到位置的问题

下面放上代码

这是一个计算自定义文字宽度的方法

public static int getTextWidth(Paint paint, String str) {
int iRet = 0;
if (str != null && str.length() > 0) {
int len = str.length();
float[] widths = new float[len];
paint.getTextWidths(str, widths);
for (int j = 0; j < len; j++) {
iRet += (int) Math.ceil(widths[j]);
}
}
return iRet;
}下面的代码是要把文字画在圆圈内的指定位置。做到无论圆圈半径多大都好。文字依然与圆圈的Y轴中线对齐
float textWidth = getTextWidth(textPaint, text);
textPaint.setColor(mTextColor);
textPaint.setTextSize(mTextSize);
canvas.drawText(text, mRadius - textWidth / 2, mRadius
- mRadius / 4, textPaint);这样得出的结果。文字会出现在y轴中线的旁边。就是因为定义了宽度再设置setTextSize的问题
只要这样改一下

textPaint.setColor(mTextColor);
textPaint.setTextSize(mTextSize);
float textWidth = getTextWidth(textPaint, text);
canvas.drawText(text, mRadius - textWidth / 2, mRadius
- mRadius / 4, textPaint);

就可以解决了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: