自定义view之canvas各种画

87 阅读1分钟
//画文字
//测量文字宽度
Rect rect = new Rect();
mTextPaint.getTextBounds(mText, 0, mText.length(), rect);
//文字居中
int x = getWidth() / 2 - rect.width() / 2;
//关于文字基线看之前的文章 : [文字基线和baseLine公式推导](https://juejin.cn/post/7138215853782204424)
canvas.drawText(mText, x, getHeight() / 2 + getBaseline(mTextPaint), mTextPaint);
//画矩形
//矩形距离坐标原点(0,0)的距离,左上角是原点,向右,下是正方向
//Rectf rectF = new RectF(left,top,right,bottom);
RectF rectF = new RectF(800, 100, 900, 200); 
canvas.drawRect(rectF, paint);
//画弧
//startAngle :起始角度,3点钟方向是0度。 sweep::扫过的范围
canvas.drawArc(rectF, 135, 270, false, mOutPaint);
// 绘制截取
// 保存画笔状态
canvas.save();
// 截取绘制的内容,待会就只会绘制clipRect设置的参数部分
canvas.clipRect(left, top, right, heigth);
canvas.drawText(mText, getWidth() / 2 - bounds.width() / 2, getHeight() / 2 + baseline, paint);
// 释放画笔状态
canvas.restore();