直接看代码就行了。
自定义得view
public class CustomView extends View {
private Path path = new Path();
private float prex;
private float prey;
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(event.getX(), event.getY());
prex = event.getX();
prey = event.getY();
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(event.getX(), event.getY());
invalidate();
default:
break;
}
return super.onTouchEvent(event);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStrokeWidth(20); //设置线得粗细大小
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
canvas.drawPath(path,paint);
}
/**
* 清除路径
*/
public void reset(){
path.reset();
invalidate();
}
}
然后是布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<com.example.customview.CustomView
android:id="@+id/cus_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
然后是我们得activity
public class MainActivity extends AppCompatActivity {
private CustomView customView;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customView = findViewById(R.id.cus_view);
btn = findViewById(R.id.btn_clear);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
customView.reset();
}
});
}
}
ok,非常easy。