public class DrawingActivity extends AppCompatActivity implements SurfaceHolder.Callback{
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private Button button;
private EditText editText;
private List<DanMu> list = new ArrayList<>();
int x = 0;
int y = 500;
Path path = new Path();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawing);
editText = findViewById(R.id.message);
surfaceView = findViewById(R.id.surface);
button = findViewById(R.id.send);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String string = editText.getText().toString();
list.add(new DanMu(string,0,150));
editText.setText("");
}
});
//触摸监听
surfaceView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//区分触摸类型
switch (event.getAction()){
//按下
case MotionEvent.ACTION_DOWN:
//把路径移到触摸的地方
path.moveTo(event.getX(),event.getY());
break;
//拖动
case MotionEvent.ACTION_MOVE:
path.lineTo(event.getX(),event.getY());
break;
}
return true;
}
});
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
//开启一个线程
new MyThread().start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
private class MyThread extends Thread{
@Override
public void run() {
//画笔对象 设置画笔属性
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(5);
paint.setTextSize(100);
paint.setStyle(Paint.Style.STROKE);
//无限循环
while (true){
//创建画板
Canvas canvas = surfaceHolder.lockCanvas();
//当画板为空时 停止
if(canvas == null){
break;
}
//canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
//弹幕
// if(list.size() > 0){
canvas.drawText(list.get(0).getText(),x+=10,y,paint);
}
//画路径
canvas.drawPath(path,paint);
//记得一点要关闭surfaceHolder
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
SurfaceView实现写字板功能
最新推荐文章于 2021-05-31 03:27:00 发布