Draw Circle on touch

后端 未结 2 1629
一向
一向 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 03:58

    The is your version with fixes to make it work:

    public class MainActivity extends Activity {
    
    LinearLayout layout;
    float x = 0;
    float y = 0;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        layout=(LinearLayout)findViewById(R.id.layout);
        layout.addView(new CustomView(MainActivity.this));
    }
    
    public class CustomView extends View {
    
        Bitmap mBitmap;
        Paint paint;
    
        public CustomView(Context context) {
            super(context);
            mBitmap = Bitmap.createBitmap(400, 800, Bitmap.Config.ARGB_8888);
            paint = new Paint();
            paint.setColor(Color.RED);
            paint.setStyle(Style.FILL);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            canvas.drawCircle(x, y, 50, paint);
        }
    
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                x = event.getX();
                y = event.getY();
                invalidate();
            }
            return false;
        }
    }
    
    }
    

提交回复
热议问题