举个栗子,我们要绘制如下效果图:
实现如下:
public class ClockView extends View {
public ClockView(Context context) {
super(context);
}
public ClockView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ClockView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
int mWidth = getMeasuredWidth();
int mHight = getMeasuredHeight();
//1.画外圆
Paint paintCircle = new Paint();
paintCircle.setStyle(Paint.Style.STROKE); //设置是否为空心
paintCircle.setAntiAlias(true); //抗锯齿
paintCircle.setStrokeWidth(5); //设置线粗细
canvas.drawCircle(mWidth / 2, mHight / 2, mWidth / 2, paintCircle);
//2.画刻度
//画刻度时,我们会发现刻度需要确定线两端的端点坐标,需要经过一系列计算才可以,所以我们选择一种简单的画法:旋转画布。
Paint paintDegree = new Paint();
paintCircle.setStrokeWidth(3);
for (int i = 0; i < 24; i++) {
//区分整点与非整点,整点线长一点
if (i == 0 || i == 6 || i == 12 || i == 18) {
paintDegree.setStrokeWidth(5);
paintDegree.setTextSize(40);
canvas.drawLine(mWidth / 2, mHight / 2 - mWidth / 2, mWidth / 2, mHight / 2 - mWidth / 2 + 60, paintDegree);
String degree = String.valueOf(i);
canvas.drawText(degree, mWidth / 2 - paintDegree.measureText(degree) / 2, mHight / 2 - mWidth / 2 + 90, paintDegree);
} else {
paintDegree.setStrokeWidth(3);
paintDegree.setTextSize(30);
canvas.drawLine(mWidth / 2, mHight / 2 - mWidth / 2, mWidth / 2, mHight / 2 - mWidth / 2 + 30, paintDegree);
String degree = String.valueOf(i);
canvas.drawText(degree, mWidth / 2 - paintDegree.measureText(degree) / 2, mHight / 2 - mWidth / 2 + 60, paintDegree);
}
//通过旋转画布简化坐标运算
canvas.rotate(15, mWidth / 2, mHight / 2);
}
//3.画指针
Paint paintCenter = new Paint();
paintCenter.setStrokeWidth(30);
paintCenter.setStyle(Paint.Style.FILL); //设置为实心
paintCircle.setAntiAlias(true); //抗锯齿
Paint paintHour = new Paint();
paintHour.setStrokeWidth(20);
Paint paintMinute = new Paint();
paintMinute.setStrokeWidth(10);
canvas.save(); //保存画布,之后所绘制内容,将在该画布之上继续绘制
canvas.translate(mWidth / 2, mHight / 2); //平移坐标原点
canvas.drawCircle(0, 0, 15, paintCenter);
canvas.drawLine(0, 0, 100, 100, paintHour);
canvas.drawLine(0, 0, 0, 100, paintMinute);
canvas.restore(); //合并图层操作,将save之前的图像和save之后的图像合并
super.onDraw(canvas);
}
最后在xml中引用
<com.example.myview.myview.ClockView
android:layout_width="match_parent"
android:layout_height="match_parent" />
学到这里,感觉的确如书中大佬们所讲,绘图方法一下子是学不完的,如何绘制的妙,还得在于不断练习,不断思考。