Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep UIView inside Circle Objective-C

How can I have my Color Selector (UIView) to stay inside a color wheel that's 300px 300px? Im using the UIPanGestureRecognizer to drag the Color Selector around the color wheel UIImageView.

The diameter of the color wheel is 300px.

Here is the image of my UIViewController:

enter image description here

The problem is that it can be dragged anywhere outside the wheel:

enter image description here

So how can I keep my UIView that hovers over the color wheel say inside the circle?

Your help is appreciated.

like image 418
atomikpanda Avatar asked Jul 29 '26 13:07

atomikpanda


1 Answers

This really seems like more of a math question. If you want to simply prevent the subview from leaving the circle then you need to insert some logic wherever you do the move code.

First find the middle of the circle. Assuming that the circle view is a clipped UIView find the center view by taking the

CGPoint center;
center.x = view.frame.origin.x + view.frame.size.width/2;
center.y = view.frame.origin.y + view.frame.size.height/2;

Then you have to calculate that distance between the touch and the center of the circle

CGPoint touch = //location of the touch point
CGFloat distance = sqrt( pow(touch.x-center.x,2)+pow(touch.y-center.y,2) )

if the distance is under 300 then you move the subview as normal

if (distance < 300) {
    //do your thing
}

if you want the view to stop moving wherever you left the circle and then snap to wherever you enter the again then you can stop here. If you want to move in the direction of your finger even when it is outside of the view then I recommend forming a vector and multiply it by 300.

CGPoint newPosition;
newPosition.x = touch.x / distance * 300;
newPosition.y = touch.y / distance * 300;

This will give you the position at the edge of the circle that is closest to the touch point.

like image 56
Andrew Hoos Avatar answered Aug 01 '26 04:08

Andrew Hoos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!