首页 > 解决方案 > 如何在某个位置单击按钮时绘制圆圈?

问题描述

我对Android很陌生,所以如果我遗漏了什么,我会提前道歉,但我的问题是我每次点击屏幕时都试图在某个位置画一个圆圈。

我尝试过记录,它确实返回了一个与我的 if 语句匹配的 int,但没有绘制任何内容。

 public boolean onTouchEvent(MotionEvent event) {
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                drawCirc = true;
                xTouch = event.getX();
                Log.d("keyboard", "xpos" + xTouch);
                yTouch = event.getY();
                break;

            case MotionEvent.ACTION_UP:
                drawCirc = false;
        }
        return true;
    }


    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        if(drawCirc) {
            if (xTouch < 150 && xTouch>0) {
                    paint.setColor(Color.RED);
                    canvas.drawCircle(150, 500, 100, paint);
                    isPlayer1 = false;
                    invalidate();
            }
        }
    }

标签: javaandroid

解决方案


@Javanator 是对的,你应该做invalidate触摸监听器。

同时,您可以尝试下面的代码,它在绘制圆圈时添加动画。

Paint paint = new Paint();

{
    paint.setColor(Color.RED);
}

// The radius of the circle you want to draw
// 0 by default
private int radius = 0;

// The animator to animate circle drawing
private ObjectAnimator radiusAnimator;

public void setRadius(int newRadius) {
    this.radius = newRadius;
    this.invalidate();
}

private void showCircle(boolean show) {
    ObjectAnimator animator = this.getRadiusAnimator();
    if (show) {
        animator.start();
    } else {
        animator.reverse();
    }
}

private ObjectAnimator getRadiusAnimator() {
    if (this.radiusAnimator == null) {
        this.radiusAnimator = ObjectAnimator.ofInt(this, "radius", 0, 100);
    }
    return this.radiusAnimator;
}


public boolean onTouchEvent(MotionEvent event) {
    switch (event.getActionMasked()) {
        case MotionEvent.ACTION_DOWN:
            // drawCirc = true;
            xTouch = event.getX();
            Log.d("keyboard", "xpos" + xTouch);
            yTouch = event.getY();
            showCircle(true);
            break;

        case MotionEvent.ACTION_UP:
            // drawCirc = false;
            showCircle(false);
    }
    return true;
}


public void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (xTouch < 150 && xTouch > 0) {
        canvas.drawCircle(xTouch, yTouch, radius, paint);
    }
    /*
    if(drawCirc) {
        if (xTouch < 150 && xTouch>0) {
                paint.setColor(Color.RED);
                canvas.drawCircle(150, 500, 100, paint);
                isPlayer1 = false;
                invalidate();
    */            
 }

推荐阅读