布局
<com.lll.shop_car.PaintView
android:id="@+id/paintView"
android:layout_width=“match_parent”
android:layout_height=“match_parent” />
PaintView页面
package com.lll.shop_car;
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;
public class PaintView extends View {
private Paint mpaint;
private Path path;
public PaintView(Context context) {
super(context);
init();
}
public PaintView(Context context,AttributeSet attrs) {
super(context, attrs);
init();
}
public PaintView(Context context,AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
//创建画笔
mpaint = new Paint();
//设置画笔为边线样式
mpaint.setStyle(Paint.Style.STROKE);
//设置画笔颜色
mpaint.setColor(Color.BLACK);
//设置边线宽度
mpaint.setStrokeWidth(5);
//新建路径
path = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//#B1F4CD
//颜色是16进制,用0x表示,代码颜色需要8位色值
//色值前两位是透明度,FF是不透明,00是透明
// 00换算为十进制0,
canvas.drawColor(0xFFB1F4CD);
canvas.drawPath(path,mpaint);//画路径
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
//手指抬起
case MotionEvent.ACTION_UP:
break;
//手指按下
case MotionEvent.ACTION_DOWN:
path.moveTo(event.getX(),event.getY());//路径移动到触摸点
break;
//手指移动
case MotionEvent.ACTION_MOVE:
path.lineTo(event.getX(),event.getY());//路径连线到移动的点
break;
}
//刷新控件回调onDraw方法
this.invalidate();
return true;
}
}
MainActivity页面
package com.lll.shop_car;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paint);
}
}