public class SignView extends View {
int painColor = Color.BLACK; //画笔颜色
float paintSize = 8;//画笔宽度
Path path;//路径
Paint paint;//画笔
float start_x, start_y, click_x, click_y;//坐标点
public SignView(Context context) {//代码new用的
this(context, null);
}
public SignView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public SignView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initPaint(); //实例化paint
}
private void initPaint() {
path = new Path();
paint = new Paint();
paint.setStrokeWidth(paintSize);
paint.setColor(painColor);
paint.setAntiAlias(true);//抗锯齿
paint.setStyle(Paint.Style.STROKE);//样式
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);//画路线
}
@Override
public boolean onTouchEvent(MotionEvent event) {
start_x = event.getX();//记录当前的坐标
start_y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
return downEvent();
case MotionEvent.ACTION_MOVE:
moveEvent();
default:
break;
}
return super.onTouchEvent(event);
}
private void moveEvent() {
click_x = start_x;
click_y = start_y;
path.quadTo(click_x, click_y, (start_x + click_x) / 2, (start_y + click_y) / 2);
invalidate();
}
private boolean downEvent() {
click_x = start_x;//保存起点坐标
click_y = start_y;
path.moveTo(start_x, start_y);//移动画笔
return true;
}
public void clear(){
if (path!=null){
path.reset();
}
invalidate();
}
}
|