How to keep a circle in another circle

I am trying to create a pad-like view in android. I have a circle that follows user gestures, and I use distance to keep a circle that goes beyond the main circle of the pad control. My problem is that I want the circle to continue to follow the gesture, but remain inside the main circle. I use a formula to find a point using angle and radius, but it does cause some funky things.

I translate the canvas, so the center of the main circle is 0, 0. Here is the code:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.translate(this.mainRadius, this.mainRadius);

    canvas.drawCircle(0, 0, this.mainRadius, this.debugPaint);
    canvas.drawCircle(this.handleX, this.handleY, this.handleRadius, this.handlePaint);
}

private void translateHandle(MotionEvent event) {
    int x = (int) (event.getX() - this.mainRadius);
    int y = (int) (event.getY() - this.mainRadius);
    double distance = distanceFromCenter(x, y);
    if (distance <= this.maxDistance) {
        this.handleX = x;
        this.handleY = y;
    } else {
        float angle = (float) Math.toDegrees(Math.atan2(y, x));
        if (angle < 0)
            angle += 360;

        this.handleX = (int) ((this.mainRadius - this.handleRadius) * Math.cos(angle));
        this.handleY = (int) ((this.mainRadius - this.handleRadius) * Math.sin(angle));
    }

    //onTranslateHandle(distance);
}

And here is the funky in the gif image: The issue animated

+4
source share
1 answer

, , , ,

private void translateHandle(MotionEvent event) {
    float x = event.getX() - this.mainRadius;
    float y = event.getY() - this.mainRadius;
    double distance = distanceFromCenter(x, y);
    if (distance > this.maxDistance) {
        // If distance is i.e 2.0 and maxDistance is 1.0 ==> adjust is 0.5
        // which repositions x and y making distance 1.0 maintaining direction
        double adjust = this.maxDistance / distance;
        x = (float)(x * adjust);
        y = (float)(y * adjust);
    }
    this.handleX = (int)x;
    this.handleY = (int)y;
}

, , .

+3

Source: https://habr.com/ru/post/1543680/


All Articles