Android使用继承View类来绘图

添加新类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 13private Paint paint; //画笔 14 15public MyView(Context context) { 16super(context); 17// TODO Auto-generated constructor stub 18paint = new Paint(); 19paint.setColor(Color.RED); //设置画笔颜色 20paint.setAntiAlias(true); //设置抗锯齿 21paint.setStyle(Style.STROKE); //设置为空心 22paint.setStrokeWidth(1); //设置空心边距为1 23paint.setTextSize(40); //设置字符串高 24} 25 26@Override 27protected void onDraw(Canvas canvas) { 28// TODO Auto-generated method stub 29super.onDraw(canvas); 30canvas.drawCircle(100, 100, 20, paint); //画个圆 31canvas.drawText("这是字符串", 0, 40, paint); //写字,指定左下角位置 32canvas.drawRect(100, 200, 200, 300, paint); //画矩形 33Path path=new Path(); //创建路径 34path.moveTo(300, 200); 35path.lineTo(300, 300); 36path.lineTo(200, 400); //指定路径 37canvas.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 9public void onCreate(Bundle savedInstanceState) { 10super.onCreate(savedInstanceState); 11MyView mv=new MyView(this); 12setContentView(mv); 13} 14 }

Android使用继承View类来绘图
文章图片

【Android使用继承View类来绘图】转载于:https://www.cnblogs.com/hzy3774/archive/2012/06/11/2544558.html

    推荐阅读