【问题标题】:Android: Circle moves to random location when tapping itAndroid:点击时圆圈会移动到随机位置
【发布时间】:2016-04-11 19:54:29
【问题描述】:

我正在编写一个程序,在手机屏幕上的随机位置画一个圆圈。它应该做的是当圆圈被触摸时,它会移除该圆圈并将其移动到另一个随机位置。

目前,当点击屏幕时,旧圆圈会被移除,并在屏幕上的另一个随机位置重新绘制。它非常接近,但我想知道我如何克服这个障碍。

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


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

    // constructors
    public Circle(Context context) {
        super(context);
        init();
    }

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

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

    void init() {
        // might be used later for some data collection
    }


    // gets random number,,
    void generateRandom() {

        int w = getWidth() - r - 50;
        int h = getHeight()- r - 50;

        int border = r + 50;

        this.x = border + random.nextInt(w-border);
        this.y = border + random.nextInt(h-border);
    }



    // when screen is tapped, old circle removed, new circle drawn
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        generateRandom();
        invalidate();
        return super.onTouchEvent(event);
    }
}

【问题讨论】:

    标签: android view ondraw ontouch


    【解决方案1】:

    这样改代码,

    @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (isInsideCircle(event.getX(), event.getY())) {
                generateRandom();
                invalidate();
            }
            return super.onTouchEvent(event);
        }
    
    
        boolean isInsideCircle(float xPoint, float yPoint) {
            float dx = (x - xPoint);
            float dxPow = (float) Math.pow(dx, 2);
            float dy = (y - yPoint);
            float dyPow = (float) Math.pow(dy, 2);
            float radPow = (float) Math.pow(r, 2);
            return (dxPow + dyPow) < radPow || (dxPow + dyPow == radPow);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多