Keep UIView inside Circle Objective-C

瘦欲@ 提交于 2020-01-13 17:23:23

问题


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.


回答1:


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.




回答2:


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)



来源:https://stackoverflow.com/questions/19335937/keep-uiview-inside-circle-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!