Android:触摸时在屏幕上随机绘制圆圈

Android: Draw random circles on screen on touch

我正在做一个项目,要求我在用户触摸屏幕时在屏幕上的随机位置画一个圆圈。当触摸事件发生时,它还需要删除我最后画的圆圈,这样屏幕上一次只能有一个圆圈。

我有一个 class 圆圈,我用它来创建一个圆圈:

public class Circle extends View {
    private final float x;
    private final float y;
    private final int r;
    private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public Circle(Context context, float x, float y, int r) {
        super(context);
        mPaint.setColor(0x000000);
        this.x = x;
        this.y = y;
        this.r = r;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(Color.RED);
        canvas.drawCircle(x, y, r, mPaint);
    }
}

这是 activity 创建新 Circle 的地方。它还将监视触摸事件。现在它正在屏幕的左上角绘制一个圆圈,但该代码需要移至 onTouch 方法中。我可能会使用 Random.

来计算随机数
public class FingerTappingActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_finger_tapping);


        LinearLayout circle = (LinearLayout) findViewById(R.id.lt);
        View circleView = new Circle(this, 300, 300, 150);
        circleView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        circle.addView(circleView);


        circle.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return true;
            }
        });

    }
}

我以前从未处理过此类触摸事件,也不知道该怎么做。一些提示将不胜感激。

做这样的事情,

public class DrawCircles extends View {

    private float x = 100;
    private float y = 100;
    private int r = 50;
    private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(Color.RED);
        canvas.drawCircle(x, y, r, mPaint);
    }

    public DrawCircles(Context context) {
        super(context);
        init();
    }

    public DrawCircles(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DrawCircles(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    void init() {
        mPaint.setColor(0x000000);
        // logic for random call here;
    }

    Random random = new Random();

    void generateRandom() {
        int minRadius = 100;
        int w = getWidth();
        int h = getHeight();
        this.x = random.nextInt(w);
        this.y = random.nextInt(h);
        this.r = minRadius + random.nextInt(100);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        generateRandom();
        invalidate();
        return super.onTouchEvent(event);
    }
}

此视图将在视图内随机绘制圆圈。为生成 x 和 y 坐标做一些调整。将此视图添加到 xml 然后它将起作用。