xcode 如何测试一个点是否在视图中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6501073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 03:59:40  来源:igfitidea点击:

How to test if a point is in a view

iphonexcodeuiviewpositioncgpoint

提问by Blane Townsend

I have a UIImageViewand I have a CGPointon the screen. I want to be able to test that point to see if it is in the UIImageView. What would be the best way to do this?

我有一个UIImageViewCGPoint屏幕上有一个。我希望能够测试该点以查看它是否在UIImageView. 什么是最好的方法来做到这一点?

回答by Deepak Danduprolu

CGPointis no good with a reference point. If your point is in window's coordinates then you can get it using

CGPoint有参考点是不行的。如果您的点在窗口的坐标中,那么您可以使用

CGPoint locationInView = [imageView convertPoint:point fromView:imageView.window];
if ( CGRectContainsPoint(imageView.bounds, locationInView) ) {
    // Point lies inside the bounds.
}

You may also call pointInside:withEvent:method

你也可以调用pointInside:withEvent:方法

if ( [imageView pointInside:locationInView withEvent:nil] ) {
    // Point lies inside the bounds
}

回答by Den

Tested in Swift 4

在 Swift 4 中测试

view.frame.contains(point)

回答by Kal

if(CGRectContainsPoint([myView frame], point))

where point is your CGPoint and myView is your UIImageView

其中 point 是你的 CGPoint 而 myView 是你的 UIImageView

回答by Mac

I'll assume you have a full-screen window (pretty reasonable, I think). Then you can transform the point from the window's coordinate space to the UIImageView's using:

我假设你有一个全屏窗口(我认为很合理)。然后,您可以使用以下命令将点从窗口的坐标空间转换为 UIImageView 的坐标空间:

CGPoint point = ...
UIWindow window = ...
UIImageView imageView = ...
CGPoint transformedPoint = [window convertPoint:point toView:imageView];

Then, you can test if the point is in the image view's frame as follows:

然后,您可以测试该点是否在图像视图的框架中,如下所示:

if(CGRectContainsPoint(imageView.frame, transformedPoint))
{
    // do something interesting....
}

回答by Darshit Shah

In Swift 3

在斯威夫特 3

let isPointInFrame = UIScreen.main.bounds.contains(newLocation)