android canvas中的save()和restore()的作用及效果

canvas.save();
//Saves the current matrix and clip onto a private stack.
保存save()之前的canvas状态

canvas.restore();
//This call balances a previous call to save(), and is used to remove all //modifications to the matrix/clip state since the last save call.

我理解为将canvas返回到save()的状态.


一个例子:用几根线画一个方向箭头,加上一个圆。
			int px = getMeasuredWidth();
			int py = getMeasuredHeight();
			
			Paint backgroundPaint = new Paint();
			backgroundPaint.setColor(Color.BLACK);
			// Draw background
			
			Paint linePaint = new Paint();
			linePaint.setColor(Color.GREEN);
			canvas.drawRect(0, 0, px, py, backgroundPaint);
			 
			canvas.save();
			canvas.rotate(180, px/2, py/2);                
			
			// Draw up arrow
			canvas.drawLine(px / 2, 0, 0, py / 2, linePaint);                
			canvas.drawLine(px / 2, 0, px, py / 2, linePaint);
			canvas.drawLine(px / 2, 0, px / 2, py, linePaint);
			 
			canvas.restore();
			 
			// Draw circle
			canvas.drawCircle(px-20, py-20, 20, linePaint);


截图效果[img]

[/img]

如果注释掉canvas.restore()。canvas.save();

效果图[img]

[/img]

根据circle位置,如果restore了恢复旋转前状态,circle位置会处于右下方。
如果没有恢复,则会跟随旋转状态到左上方。

参考:http://www.cnblogs.com/xirihanlin/archive/2009/07/24/1530246.html

猜你喜欢

转载自hellorheaven.iteye.com/blog/1617160