首先须要建立一个继承View的类,并在这个类中重写onDraw()方法---负责绘制小球,还须要重写onTouuch(Motion event)方法---负责小球随手指移动的事件,当手指移动时,须要使用invalidate()方法来通知组件从新绘制android
public class CustomView extends View { public float currentX = 40; public float currentY = 50; //定义、并建立画笔 Paint paint = new Paint(); public CustomView(Context context) { super(context); } public CustomView(Context context, AttributeSet attrs) { super(context, attrs); } public CustomView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //设置画笔的颜色 paint.setColor(Color.RED); //绘制一个圆 圆心的X坐标,圆心的Y坐标,圆心的半径,绘制圆的画笔 canvas.drawCircle(currentX, currentY, 15, paint); } //重写触摸事件,编写自定义的触摸处理方法 @Override public boolean onTouchEvent(MotionEvent event) { //修改currentX,currentY的两个属性 currentX = event.getX(); currentY = event.getY(); //通知当前组件重绘 invalidate(); //返回true表示该处理方法已经处理事件 return true; } }
第二步就是自定义view的使用canvas
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.dkt.myapplication.CustomView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>