Android通过onDraw实现在View中绘图操作

Android绘图操作,通过继承View实现,在onDraw函数中实现绘图。

下面是一个简单的例子:

 1 public class AndroidTest extends Activity {
 2     /** Called when the activity is first created. */
 3     @Override
 4     public void onCreate(Bundle savedInstanceState) {
 5         super.onCreate(savedInstanceState);
 6         
 7         MyView mv = new MyView(this);
 8         setContentView(mv);
 9     }
10     
11     public class MyView extends View {
12 
13         MyView(Context context) {
14             super(context);
15         }
16         
17         @Override
18         protected void onDraw(Canvas canvas) {
19             // TODO Auto-generated method stub
20             super.onDraw(canvas);
21             
22             // 首先定义一个paint 
23             Paint paint = new Paint(); 
24 
25             // 绘制矩形区域-实心矩形 
26             // 设置颜色 
27             paint.setColor(Color.BLUE); 
28             // 设置样式-填充 
29             paint.setStyle(Style.FILL); 
30             // 绘制一个矩形 
31             canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), paint); 
32 
33             // 绘空心矩形 
34             // 设置颜色 
35             paint.setColor(Color.RED); 
36             // 设置样式-空心矩形 
37             paint.setStyle(Style.STROKE); 
38             // 绘制一个矩形 
39             canvas.drawRect(new Rect(10, 10, 100, 30), paint); 
40 
41             // 绘文字 
42             // 设置颜色 
43             paint.setColor(Color.GREEN); 
44             // 绘文字 
45             canvas.drawText("Hello", 10, 50, paint); 
46 
47             // 绘图 
48             // 从资源文件中生成位图 
49             Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon); 
50             // 绘图 
51             canvas.drawBitmap(bitmap, 10, 60, paint); 
52         }
53         
54     }
55 }

 

posted @ 2013-10-09 13:07  佬D  阅读(1310)  评论(0编辑  收藏  举报