3. 使用绘图API自定义视图 --- 旋转的方块

 1 import android.content.Context;
 2 import android.graphics.Canvas;
 3 import android.graphics.Color;
 4 import android.graphics.Paint;
 5 import android.util.AttributeSet;
 6 import android.view.View;
 7 
 8 /**
 9  * 旋转的方块
10  * 
11  * @author dr
12  */
13 public class RotatingRect extends View {
14 
15     private Paint p; // 画笔对象
16     private float degrees = 0;
17 
18     /** 资源解析程序来使用的 */
19     public RotatingRect(Context context, AttributeSet attrs, int defStyleAttr) {
20         super(context, attrs, defStyleAttr);
21 
22         initProperties();
23     }
24 
25     public RotatingRect(Context context, AttributeSet attrs) {
26         super(context, attrs);
27 
28         initProperties();
29     }
30 
31     public RotatingRect(Context context) {
32         super(context);
33 
34         initProperties();
35     }
36 
37     /** 初始化属性 */
38     private void initProperties() {
39         p = new Paint();
40         p.setColor(Color.RED);   // 设置红色
41     }
42 
43     @Override
44     public void draw(Canvas canvas) {
45         super.draw(canvas);
46 
47         canvas.save();  // 保存状态
48         // canvas.rotate(degrees);   // 绕着左上角旋转
49         canvas.translate(200, 200);  // 调整位置,为了显示全。
50         canvas.rotate(degrees, 50, 50);  // 绕着中心点旋转。
51         // 0, 0, 100, 100 距离边界的值。
52         canvas.drawRect(0, 0, 100, 100, p);
53 
54         degrees++;
55         canvas.restore();  // 恢复
56 
57         // 使其无效。所以再重绘的时候,查看这个view是否是有效状态,
58         invalidate();  
59     }
60 
61 }
1 <com.jikexueyuan.drawapi.RotatingRect
2         android:layout_width="fill_parent"
3         android:layout_height="fill_parent" />
原文地址:https://www.cnblogs.com/androidsj/p/3945642.html