Draw Circle on touch

后端 未结 2 1628
一向
一向 2020-11-30 03:52

I am trying to draw a circle where user touches screen .

public class MainActivity extends Activity implements OnTouchListener {

LinearLayout layout;
float         


        
2条回答
  •  醉酒成梦
    2020-11-30 03:59

    I would do it this way:

    public class TestActivity extends Activity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(new DrawingView(this));
        }
    
        class DrawingView extends SurfaceView {
    
            private final SurfaceHolder surfaceHolder;
            private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    
            public DrawingView(Context context) {
                super(context);
                surfaceHolder = getHolder();
                paint.setColor(Color.RED);
                paint.setStyle(Style.FILL);
            }
    
            @Override
            public boolean onTouchEvent(MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (surfaceHolder.getSurface().isValid()) {
                        Canvas canvas = surfaceHolder.lockCanvas();
                        canvas.drawColor(Color.BLACK);
                        canvas.drawCircle(event.getX(), event.getY(), 50, paint);
                        surfaceHolder.unlockCanvasAndPost(canvas);
                    }
                }
                return false;
            }
        }
    }
    

提交回复
热议问题