MSurfaceView: public class MSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Runnable { private SurfaceHolder mHolder; private Canvas mCanvas; private boolean mIsDrawing; Path path = new Path(); Paint paint = new Paint(); float x, y; public MSurfaceView(Context context) { this(context, null); } public MSurfaceView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } private void initView() { mHolder = getHolder(); mHolder.addCallback(this); setFocusable(true); setFocusableInTouchMode(true); setKeepScreenOn(true); paint.setColor(Color.RED); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(2); } @Override public void surfaceCreated(SurfaceHolder holder) { mIsDrawing = true; new Thread(this).start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { mIsDrawing = false; } @Override public void run() { long startTime = System.currentTimeMillis(); while (mIsDrawing) { draw(); x++; y = (float) (100 * Math.sin(x * 2 * Math.PI / 180) + 400); path.lineTo(x, y); long endTime = System.currentTimeMillis(); if (endTime - startTime < 100) { try { Thread.sleep(100 - (endTime - startTime)); } catch (InterruptedException e) { e.printStackTrace(); } } } } private void draw() { try { //get canvas mCanvas = mHolder.lockCanvas(); //draw... mCanvas.drawColor(Color.WHITE); mCanvas.drawPath(path, paint); } catch (Exception e) { } finally { //submit if (mCanvas != null) { mHolder.unlockCanvasAndPost(mCanvas); } } }@Override public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: path.moveTo(x, y); break; case MotionEvent.ACTION_MOVE: path.lineTo(x, y); break; case MotionEvent.ACTION_UP: break; } return true; }}
使用SurfaceView模拟写字板
最新推荐文章于 2020-07-06 19:54:01 发布