標籤:
相信很多人和我一樣看了官方文檔對Canvas save(), restore()方法的解釋還是一個頭霧水,save()儲存的到底是什麼資訊呢?
答案是:座標系的原點,座標軸方向的資訊。
我們在使用Canvas時難免會用到transitoin(), rotate()方法來改變座標系的原點和座標軸的方向,save()儲存的正是這些資訊。
下面舉個栗子:
該例子用Canvas繪製一個儀錶盤。自訂View,在onDraw()方法中繪製該儀錶盤。
1 /** 2 * Created by Administrator on 2015/2/1 0001. 3 */ 4 public class ImageMatrixView extends View { 5 6 7 public ImageMatrixView(Context context) { 8 super(context); 9 10 }11 12 public ImageMatrixView(Context context, AttributeSet attrs) {13 super(context, attrs);14 15 }16 1719 @TargetApi(Build.VERSION_CODES.LOLLIPOP)20 @Override21 protected void onDraw(Canvas canvas) {22 super.onDraw(canvas);23 //畫筆用於繪製圓和刻度24 Paint paintLine = new Paint();25 paintLine.setColor(Color.BLUE);26 paintLine.setStyle(Paint.Style.STROKE);27 paintLine.setTextSize(20);28 //畫筆用於繪製指標29 Paint paintPointer = new Paint();30 paintPointer.setStrokeWidth(10);31 //擷取圓的半徑32 float radius = Math.min(getWidth() / 2, getHeight() / 2);33 34 //畫圓周35 canvas.drawCircle(radius, radius, radius, paintLine);36 //變化座標系,改變後,座標原點在(radius, radius),x軸正方形水平向右,y軸正方向水平向下37 canvas.translate(radius, radius);38 39 //儲存座標系資訊40 canvas.save();41 42 //畫圓上的點43 for (int i = 0; i < 12; i++)44 {45 if (i % 3 == 0)46 {47 canvas.drawLine(0, -radius, 0, - (radius - 20), paintLine);48 }49 else50 {51 canvas.drawLine(0, -radius, 0, -(radius - 10), paintLine);52 }53 canvas.drawText(String.valueOf(i), 0, - (radius - 24), paintLine);54 //將座標系順時針旋轉30度,55 canvas.rotate(30, 0, 0);56 }57 58 //回到上次儲存的狀態:座標原點在(radius, radius),x軸正方向水平向右,y軸正方向水平向下59 canvas.restore();
//在儲存的狀態上繼續改變座標軸60 canvas.rotate(30);
//繪製指標61 canvas.drawLine(0, 0, 40, 0, paintPointer);62 canvas.rotate(30);63 canvas.drawLine(0, 0, 60, 0, paintLine);67 }68 }
:
Android-Canvas.save() Canvas.restore() 總結