首先是介绍一下是怎么画图!
有两个类Canvas,Paint;
Canvas代表了“依附”了指定View的画布,Paint 代表了Canvas上的画笔;
如何在Android应用中绘制基本的集合图形,关键在于一个自定义View组件,要重写View组件的onDraw(Canvase)方法,接下来是在该 Canvas上绘制大量的几何图形,球形,方块,线,等各种形状!
画球: Canvas.drawCircle(x,y,len,paint)
为球绑上Touch事件;
原码如下:
CustomView类:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //获取布局文件中的LinearLayout容器 LinearLayout root = (LinearLayout)findViewById(R.id.root); //创建DrawView组件 final DrawView draw =new DrawView(this); //设置自定义组件的最大宽度、高度 draw.setMinimumWidth(300); draw.setMinimumHeight(500); //为draw组件绑定Touch事件 draw.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent event) { //修改draw组件的currentX、currentY两个属性 draw.currentX = event.getX(); draw.currentY = event.getY(); //通知draw组件重绘 draw.invalidate(); //返回true表明处理方法已经处理该事件 return true; } }); root.addView(draw); }
DrawView类:
public float currentX = 40; public float currentY = 50; /** * @param context */ public DrawView(Context context) { super(context); // TODO Auto-generatedconstructor stub } @Override public void onDraw (Canvas canvas) { super.onDraw(canvas); //创建画笔 Paint p = new Paint(); //设置画笔的颜色 p.setColor(Color.GREEN); //绘制一个小圆(作为小球) canvas.drawCircle(currentX , currentY , 15 , p); }