/*
* 这个demon演示了测量字符串长度的方法。字符串最终的大小是和绘制文字的字体的类型和字体的大小都有关,
* 字体的类型和大小都是通过Paint对象来设置的setTypeface,setTextSize。
* getTextWidths 可以提供widths数组返回text字符串中对应的每个字符使用当前字体绘制的宽度。
* 而measureText则返回整个字符串的宽度。getTextBounds则是返回字符串占据的矩形区域大小。
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
private static final int WIDTH = 50;
private static final int HEIGHT = 50;
private static final int STRIDE = 64;
// 设置每个像素的颜色值
private int[] createColors() {
int[] colors = new int[STRIDE * HEIGHT];
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
int r = x * 255 / (WIDTH - 1);
int g = y * 255 / (HEIGHT - 1);
int b = 255 - Math.min(r, g);
int a = Math.max(r, g);
colors[y * STRIDE + x] = (a << 24) | (r << 16) | (g << 8) | b;
}
}
return colors;
}
private class SampleView extends View{
private Paint mPaint;
private float mOriginX=10;
private float mOriginY=80;
public SampleView(Context context) {
super(context);
setFocusable(true);
mPaint=new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(5);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setTextSize(64);
//设置字体的类型
mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.ITALIC));
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
canvas.translate(mOriginX, mOriginY);
//因为我们所定制的底框与字符串的边框相同,所以排列规则的效果不明显
showText(canvas,"Measure",Paint.Align.LEFT);
canvas.translate(0, 80);
showText(canvas,"Wiggy",Paint.Align.CENTER);
canvas.translate(0, 80);
showText(canvas,"Text",Paint.Align.RIGHT);
}
private void showText(Canvas canvas, String text, Align align) {
Rect bounds=new Rect();
float[] widths=new float[text.length()];
//将每个字符的宽度放到widths数组中,并返回text中字符的个数
int count=mPaint.getTextWidths(text, 0, text.length(), widths);
//获取字符串的宽度
float w=mPaint.measureText(text, 0, text.length());
mPaint.getTextBounds(text, 0, text.length(), bounds);
mPaint.setColor(0xFF88FF88);
//绘制底框
canvas.drawRect(bounds, mPaint);
mPaint.setColor(Color.BLACK);
canvas.drawText(text, 0, 0, mPaint);
//定义字符串下面圆点的坐标,每个点由x、y两个值表示,所以数组的长度为2+count*2
float[] pts=new float[2+count*2];
float x=0;
float y=0;
pts[0]=x;
pts[1]=y;
for(int i=0;i<count;i++){
//用两个点表示每个字符的宽度
x+=widths[i];
//从第三个值开始
pts[2+2*i]=x;
//在绘制字符图形时以是字符的基准线为基准的。比如canvas.drawText(text, 0, 0, mPaint);
//且字符的排列方式设定为左对齐则表示字符串的基准线为x轴
pts[2+2*i+1]=y;
}
mPaint.setColor(Color.RED);
mPaint.setStrokeWidth(0);
//沿字符的基准线绘制一条线
canvas.drawLine(0, 0, w, 0, mPaint);
mPaint.setStrokeWidth(5);
//在线上用圆点将每个字符间隔开
//(count+1)<<1=2+count*2
canvas.drawPoints(pts, 0, (count+1)<<1, mPaint);
}
}
}
Android Api Demos登顶之路(七十八)Graphics-->MeansureText
最新推荐文章于 2017-07-20 22:23:43 发布