先直接上代码:
step1.建立drawview.java
package com.example.joky27.customview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by joky27 on 2017/4/17.
*/
public class DrawView extends View{
public float currentx=40;
public float currenty=50;
public float prex;
public float prey;
//之前坐标
private Path mpath= new Path();//定义路径
public Paint p; //定义画笔
public DrawView (Context context)
{
super( context);
}
public DrawView(Context context,AttributeSet set)
{
super(context,set);
mycontext=context;
p= new Paint();
p.setColor(Color.RED);
p.setStyle(Paint.Style.STROKE);//将画笔设置为空心,才会画成曲线
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeWidth(5);//设置画笔宽度
p.setAntiAlias(true);
}
@Override
public void onDraw(Canvas canvas){
super.onDraw(canvas);
Paint m=new Paint();
m.setColor(Color.BLUE);
canvas.drawCircle(currentx,currenty,15,m);
canvas.drawPath(mpath,p);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{ //不断触发触摸屏事件,将监听到的信息都传入DrawView 组件
currentx=event.getX();
currenty=event.getY();
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
mpath.moveTo(currentx,currenty);
prex = currentx;
prey = currenty;
break;
case MotionEvent.ACTION_MOVE:
mpath.quadTo(prex,prey,currentx,currenty);
prex = currentx;
prey = currenty;
break;
case MotionEvent.ACTION_UP:
mpath.reset();
break;
}
invalidate();
return true;
}
} step2.建立activity_main.xml
step3.直接创建mainactivity.java,将activity_main.xml传入
package com.example.joky27.customview;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
主要思路及注意点:
1.设置paint()的style,这里用了两个画笔,画小球用的是蓝色实心,而画路径用的是红色空心(不设为空心画不了曲线)
2.重写onTouchevent中,invalidate()屏幕刷新,当动作为action_up时,重设路径,所以效果是当手指离开触摸屏,之前的轨迹被清屏。
void invalidate ()
Invalidate the whole view. If the view is visible, onDraw(android.graphics.Canvas) will be called at some point in the future.
This must be called from a UI thread. To call from a non-UI thread, call postInvalidate(). -------------https://developer.android.com/reference/android/view/View.html