android小Demo--圆球跟随手指轨迹移动
eatwhatApp的客户端基本实现,会再后续进行整改,今天做一个在网上找到的小Demo,让屏幕中出现一个圆球,并跟随手指移动。
写个java类DrawView继承于View:
public class DrawView extends View { public DrawView(Context context) { super(context); } }
定义属性:
//画笔 private Paint paint; //当前X坐标 private float currentX; //当前Y坐标 private float currentY; public DrawView(Context context) { super(context); this.paint = new Paint(); this.currentX = 100; this.currentY = 100; }
重写onDraw()方法:
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //设置画笔颜色 paint.setColor(Color.RED); //绘制圆形,中心位置(currentX, currentY),半径10 canvas.drawCircle(currentX, currentY, 10, paint); }
重写onTouchEven()方法:
@Override public boolean onTouchEvent(MotionEvent event) { //获取点击事件的坐标x,y currentX = event.getX(); currentY = event.getY(); //重绘控件 invalidate(); return true; }
之后变可以在activity中实例化该控件:
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout); DrawView draw = new DrawView(this); layout.addView(draw);
这样便完成了该demo。
比大多数人的努力程度之低,根本轮不到拼天赋...
宝宝巴士 SD.Team