- 使用canvas的平移画布的操作,实际上是改变屏幕坐标原点在Canvas当前图层的位置
- 所以当我们移动canvas时,之前绘制的图形并不受影响(之前绘制的图层好像黏在了屏幕上),不会跟着移动
- 可以使用save()保存canvas的状态,使用restore()恢复保存的状态
使用canvas的平移旋转等操作实现如下效果:
code:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by feathers on 16-11-17.
*/
public class Clock extends View{
private Paint mPaint;
private int mWidth;
private int mHeight;
public Clock(Context context) {
super(context);
}
public Clock(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Clock(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = getMeasuredWidth();
mHeight = getMeasuredHeight();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 绘制外圆
mPaint = new Paint();
mPaint.setStyle(Paint.Style.STROKE); // 不填重 划线
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(5);
canvas.drawCircle(mWidth / 2, mHeight / 2, mWidth / 2, mPaint);
// 绘制刻度
mPaint.setStrokeWidth(3);
for (int i = 0; i < 24; i++) {
// 绘制刻度
if (i == 0 || i == 6 || i == 12 || i == 18) {
mPaint.setStrokeWidth(5);
mPaint.setTextSize(30);
canvas.drawLine(mWidth / 2, mHeight / 2 - mWidth / 2,
mWidth / 2, mHeight / 2 - mWidth / 2 + 60,
mPaint);
} else {
mPaint.setStrokeWidth(3);
mPaint.setTextSize(15);
canvas.drawLine(mWidth/2, mHeight/2 - mWidth/2,
mWidth/2,mHeight/2 - mWidth/2 + 60,
mPaint);
}
// 绘制文字
String degree = String.valueOf(i);
canvas.drawText(degree,
mWidth / 2 - mPaint.measureText(degree) / 2,
mHeight / 2 - mWidth / 2 + 90,
mPaint);
// 旋转画布,简化坐标运算
canvas.rotate(15, mWidth / 2, mHeight / 2);
}
// 绘制指针,同样是线段
Paint paintHour = new Paint();
paintHour.setStrokeWidth(20);
Paint paintMinute = new Paint();
paintMinute.setStrokeWidth(10);
canvas.save();
canvas.translate(mWidth / 2, mHeight / 2); // 平移的是屏幕的坐标系,而不是画布
canvas.drawLine(0, 0, 100, 100, paintHour);
canvas.drawLine(0, 0, 100, 200, paintMinute);
canvas.restore(); // 恢复保存时的状态
}
}