UIView控件坐标系转换

版权声明:未经本人允许,禁止转载.

1.坐标转换方法

  1. 将point由point所在的视图转换到目标视图view中,返回在目标视图view中的point
    - (CGPoint)convertPoint:(CGPoint)point toView:(nullable UIView *)view;
  2. 将point从view中转换到当前视图,返回在当前视图中的point
    - (CGPoint)convertPoint:(CGPoint)point fromView:(nullable UIView *)view;
  3. 将rect由rect所在的视图转换到目标视图view中,返回在目标视图view中的rect
    - (CGRect)convertRect:(CGRect)rect toView:(nullable UIView *)view;
  4. 将rect从view中转换到当前视图,返回在当前视图中的rect
    - (CGRect)convertRect:(CGRect)rect fromView:(nullable UIView *)view;
    注:toView中的view == nil时,view为[UIApplication sharedApplication].keyWindow;

2.同一坐标系的比较

  1. 判断 rect1是否包含 rect2,返回bool
    BOOL isContain = CGRectContainsRect(rect1, rect2);
  2. 判断 rect1和 rect2是否有重叠,返回bool
    BOOL isIntersect = CGRectIntersectsRect(rect1, rect2);
  3. 判断点point是否在rect中,返回bool
    BOOL isContain = CGRectContainsPoint(rect, point);

实例1:判断UIView控件是否在主窗口上

方法写在UIView的Category中

- (BOOL)isShowingOnKeyWindow {
    //主窗口
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;

    //以主窗口左上角为坐标原点,计算self的矩形框
    CGRect newFrame = [keyWindow convertRect:self.bounds fromView:self];
    CGRect winBounds = keyWindow.bounds;

    //主窗口的bounds 和 self的矩形框 是否有重叠
    BOOL intersects = CGRectIntersectsRect(newFrame, winBounds);

    return !self.isHidden && self.alpha > 0.01 && self.window == keyWindow && intersects;
}

实例2:判断两个View是否有重叠

方法写在UIView的Category中
- (BOOL)intersectWithView:(UIView *)view {
//主窗口
UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
//以主窗口左上角为坐标原点,计算self和view的矩形框
CGRect selfRect = [self convertRect:self.bounds toView:keyWindow];
CGRect viewRect = [view convertRect:view.bounds toView:keyWindow];
//返回是否有重叠的结果
return CGRectIntersectsRect(selfRect, viewRect);
}

你可能感兴趣的:(UIView控件坐标系转换)