在調用畫布的save()方法之后,可以對畫布進行平移、旋轉等操作,
然后再將需要畫的內容draw到畫布上去,
最后再調用restore()方法,恢復到調用save()方法之前的狀態。
1
public
class
SubView
extends
TextView {
2
3
public
SubView(Context context, AttributeSet attrs) {
4
super
(context, attrs);
5
}
6
7
protected
void
onDraw(android.graphics.Canvas canvas) {
8
int
px
=
getMeasuredWidth();
9
int
py
=
getMeasuredHeight();
10
11
Paint backgroundPaint
=
new
Paint();
12
backgroundPaint.setColor(Color.CYAN);
13
canvas.drawRect(
0
,
0
, px, py, backgroundPaint);
14
15
canvas.save();
16
//
順時針旋轉180度
17
canvas.rotate(
180
, px
/
2
, py
/
2
);
18
19
Paint linePaint
=
new
Paint();
20
linePaint.setColor(Color.RED);
21
22
canvas.drawLine(px
/
2
,
0
,
0
, py
/
2
, linePaint);
23
canvas.drawLine(px
/
2
,
0
, px, py
/
2
, linePaint);
24
canvas.drawLine(px
/
2
,
0
, px
/
2
, py, linePaint);
25
26
//
恢復到調用save()方法之前的狀態
27
//
即沒有順時針旋轉180度
28
canvas.restore();
29
30
canvas.drawCircle(px
-
20
, py
-
20
,
20
, linePaint);
31
};
32
}
在這個例子中,調用save()方法之后,將畫布進行順時針旋轉了180度,畫了三條線段,
然后調用restore()方法恢復到順時針旋轉180度之前,再畫一個實心圓。
布局文件內容:
1
<
RelativeLayout
xmlns:android
="http://schemas.android.com/apk/res/android"
2
xmlns:tools
="http://schemas.android.com/tools"
3
android:layout_width
="match_parent"
4
android:layout_height
="match_parent"
>
5
6
<
com.example.test.SubView
7
android:layout_margin
="20dip"
8
android:layout_width
="fill_parent"
9
android:layout_height
="fill_parent"
10
android:layout_centerHorizontal
="true"
11
android:layout_centerVertical
="true"
12
tools:context
=".MainActivity"
/>
13
14
</
RelativeLayout
>
程序運行之后的屏幕截圖:

