XML布局:
<SurfaceView
android:id="@+id/main_surface"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Activity中的代码:
public class MainActivity extends AppCompatActivity {
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private Path path=new Path();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//查找控件
surfaceView=findViewById(R.id.main_surface);
//获得SurfaceHolder
surfaceHolder=surfaceView.getHolder();
//鼠标的监听
surfaceView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
Log.e("#####","1111111111111");
if(motionEvent.getAction()==MotionEvent.ACTION_DOWN){
//鼠标落下的时候
Log.e("#####","22222222");
path.moveTo(motionEvent.getX(),motionEvent.getY());
}else if(motionEvent.getAction()==MotionEvent.ACTION_MOVE){
//鼠标移动的时候
Log.e("#####","3333333");
path.lineTo(motionEvent.getX(),motionEvent.getY());
}
return true;
}
});
//重写方法
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
//while(true)属于耗时操作 在子线程中执行
new MyThread().start();
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
}
});
}
class MyThread extends Thread{
@Override
public void run() {
super.run();
//画笔
Paint paint = new Paint();
//画笔的大小
paint.setTextSize(30);
paint.setStyle(Paint.Style.STROKE);
while (true){
//三原色
int a =(int)(Math.random()*255);
int a1 =(int)(Math.random()*255);
int a2 =(int)(Math.random()*255);
//执行三原色
int argb = Color.argb(255, a, a1, a2);
paint.setColor(argb);
//开启画布
Canvas canvas = surfaceHolder.lockCanvas();
//清空画布
canvas.drawColor(Color.WHITE, PorterDuff.Mode.CLEAR);
//货值路径
Log.i("lyj",""+path);
canvas.drawPath(path,paint);
//关闭画布
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}