关于canvas的save()及restore()方法

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.SurfaceView;

public class MyView1 extends SurfaceView
{

	private Bitmap mBitmap;

	private Paint mPaint;

	public MyView1(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		mPaint = new Paint();
		this.initBitmap();
	}

	private void initBitmap()
	{
		mBitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.ic_launcher);
	}

	@Override
	public void draw(Canvas canvas)
	{
		super.draw(canvas);

		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();

		mPaint.setColor(Color.GREEN);
		canvas.drawRect(200, 10, 250, 100, mPaint);
	}

}

 上图代码绘制出的view如下图:

关于canvas的save()及restore()方法

如掉save和restore方法(38和42行),意味着绿色的图形也受到38和42行之间,对canvas操作的代码影响,也会旋转,如下图:

关于canvas的save()及restore()方法

你可能感兴趣的:(canvas)