如何测试点是否在视图中

Bla*_*end 24 iphone xcode position uiview cgpoint

我有一个UIImageView,我CGPoint在屏幕上有一个.我希望能够测试这一点,看看它是否在UIImageView.最好的方法是什么?

Dee*_*olu 48

CGPoint参考点并不好.如果您的点位于窗口坐标中,那么您可以使用它

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

你也可以打电话给pointInside:withEvent:方法

if ( [imageView pointInside:locationInView withEvent:nil] ) {
    // Point lies inside the bounds
}
Run Code Online (Sandbox Code Playgroud)


Den*_*Den 6

在Swift 4中测试

view.frame.contains(point)
Run Code Online (Sandbox Code Playgroud)