经过一些(数小时)的实验,我想出了这个解决方案:
// return the part of the passed view that is visible
- (CGRect)getVisibleRect:(UIView *)view {
// get the root view controller (and it's view is vc.view)
UIViewController *vc = UIApplication.sharedApplication.keyWindow.rootViewController;
// get the view's frame in the root view's coordinate system
CGRect frame = [vc.view convertRect:view.frame fromView:view.superview];
// get the intersection of the root view bounds and the passed view frame
CGRect intersection = CGRectIntersection(vc.view.bounds, frame);
// adjust the intersection coordinates thru any nested views
UIView *loopView = view;
do {
intersection = [loopView convertRect:intersection fromView:loopView.superview];
loopView = loopView.superview;
} while (loopView != vc.view);
return intersection; // may be same as the original view frame
}
我首先尝试将根视图转换为目标视图的坐标,然后在视图框架上执行 CGRectIntersect,但没有成功。但是我让它以相反的方式为 UIViews 以根视图作为它们的父视图。然后经过一番探索,我发现我必须通过视图层次结构导航子视图。
它适用于超级视图是根视图的 UIView,也适用于作为其他视图的子视图的 UIView。
我通过在初始视图上围绕这些可见矩形绘制边框对其进行了测试,并且效果很好。
但是...如果 UIView 被缩放 (!=1) 和另一个 UIView 的子视图而不是根视图,它就不能正常工作。结果可见矩形的原点偏移了一点。如果视图位于子视图中,我尝试了几种不同的方法来调整原点,但我无法找到一种干净的方法。
我已将此方法添加到我的实用程序 UIView 类别中,以及我一直在开发或获取的所有其他“缺失”的 UIView 方法。 (Erica Sadun的变换方法……我不配……)
这确实解决了我正在解决的问题。所以我将发布另一个关于缩放问题的问题。
编辑:
在处理扩展问题的问答时,我也为这个问题想出了一个更好的答案:
// return the part of the passed view that is visible
- (CGRect)getVisibleRect:(UIView *)view {
// get the root view controller (and it's view is vc.view)
UIViewController *vc = UIApplication.sharedApplication.keyWindow.rootViewController;
// get the view's frame in the root view's coordinate system
CGRect rootRect = [vc.view convertRect:view.frame fromView:view.superview];
// get the intersection of the root view bounds and the passed view frame
CGRect rootVisible = CGRectIntersection(vc.view.bounds, rootRect);
// convert the rect back to the initial view's coordinate system
CGRect visible = [view convertRect:rootVisible fromView:vc.view];
return visible; // may be same as the original view frame
}