添加新类MyView继承View
在MyView中实例化Paint
1 package com.hu.viewdemo; 2 3 import android.content.Context; 4 import android.graphics.Canvas; 5 import android.graphics.Color; 6 import android.graphics.Paint; 7 import android.graphics.Paint.Style; 8 import android.graphics.Path; 9 import android.view.View; 10 11 public class MyView extends View{ 12 13 private Paint paint;//画笔 14 15 public MyView(Context context) { 16 super(context); 17 // TODO Auto-generated constructor stub 18 paint = new Paint(); 19 paint.setColor(Color.RED);//设置画笔颜色 20 paint.setAntiAlias(true);//设置抗锯齿 21 paint.setStyle(Style.STROKE);//设置为空心 22 paint.setStrokeWidth(1);//设置空心边距为1 23 paint.setTextSize(40);//设置字符串高 24 } 25 26 @Override 27 protected void onDraw(Canvas canvas) { 28 // TODO Auto-generated method stub 29 super.onDraw(canvas); 30 canvas.drawCircle(100, 100, 20, paint);//画个圆 31 canvas.drawText("这是字符串", 0, 40, paint);//写字,指定左下角位置 32 canvas.drawRect(100, 200, 200, 300, paint);//画矩形 33 Path path=new Path();//创建路径 34 path.moveTo(300, 200); 35 path.lineTo(300, 300); 36 path.lineTo(200, 400);//指定路径 37 canvas.drawPath(path, paint);//沿路径绘图 38 } 39 40 }
然后在activity类中将MyView的实例设为ContentView
1 package com.hu.viewdemo; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 6 public class ViewDemoActivity extends Activity { 7 /** Called when the activity is first created. */ 8 @Override 9 public void onCreate(Bundle savedInstanceState) { 10 super.onCreate(savedInstanceState); 11 MyView mv=new MyView(this); 12 setContentView(mv); 13 } 14 }