在讀android SDK裡面的samples裡面游戲的時候,很多時候都看到對canvas的save()和restore()運用。
下面是個小程序,使用了這兩個方面,使得旋轉紅色方塊的時候,保證藍色方塊不受影響。
Java代碼
- package com.ray.test;
-
- import android.app.Activity;
- import android.content.Context;
- import android.graphics.Canvas;
- import android.graphics.Color;
- import android.graphics.Paint;
- import android.os.Bundle;
- import android.vIEw.SurfaceHolder;
- import android.view.SurfaceVIEw;
-
- public class Test extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(new MyVIEw(this));
- }
-
- class MyView extends SurfaceVIEw implements SurfaceHolder.Callback{
-
- private SurfaceHolder mHolder;
- private Canvas canvas;
- public MyVIEw(Context context) {
- super(context);
- mHolder = getHolder();
- mHolder.addCallback(this);
- }
-
- @Override
- public void surfaceChanged(SurfaceHolder holder, int format, int width,
- int height) {
-
- }
-
- @Override
- public void surfaceCreated(SurfaceHolder holder) {
- canvas = mHolder.lockCanvas();
- Paint mPaint = new Paint();
- mPaint.setColor(Color.BLUE);
- canvas.drawRect(100, 200, 200, 300, mPaint);
-
- canvas.save();
- canvas.rotate(45);
- mPaint.setColor(Color.RED);
- canvas.drawRect(150, 10, 200, 60, mPaint);
- canvas.restore();
- mHolder.unlockCanvasAndPost(canvas);
- }
-
- @Override
- public void surfaceDestroyed(SurfaceHolder holder) {
- // TODO Auto-generated method stub
-
- }
-
- }
- }