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
:
The problem is that it can be dragged anywhere outside the wheel:
So how can I keep my UIView
that hovers over the color wheel say inside the circle?
Your help is appreciated.
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.
Calculate the pythagorean distance from the center, and stop the indicator from being dragged any further than the desired radius. You can even pre-calculate the square of the radius once, and compare against that, in order to avoid doing square roots.
(distance squared = delta x squared + delta y squared)