Android-Canvas.save() Canvas.restore() 總結

來源:互聯網
上載者:User

標籤:

相信很多人和我一樣看了官方文檔對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() 總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.