首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 獲取兩個 UIView 包含關係的最小矩形區域

     編輯:程式設計綜合問答

需求澄清

「兩個 UIView 最小的矩形」通常指:**包含兩個 View 的最小外接矩形** (Bounding Box),即兩者 frame 的并集。

計算方法


- (CGRect)boundingRectOfView:(UIView *)view1 andView:(UIView *)view2 {
    // 確保兩個 view 在同一坐標系 (同一 superview 或轉換到同一座標系)
    CGRect frame1 = [view1.superview convertRect:view1.frame fromView:view1.superview];
    CGRect frame2 = [view2.superview convertRect:view2.frame fromView:view2.superview];
    // 若已在同一 superview,直接用 view1.frame, view2.frame
    
    // 計算并集 (最小外接矩形)
    CGRect unionRect = CGRectUnion(frame1, frame2);
    return unionRect;
}

在 drawRect: 中繪製該矩形


- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // 獲取兩個子視圖 (假設已添加為子視圖)
    UIView *view1 = [self viewWithTag:100];
    UIView *view2 = [self viewWithTag:101];
    if (!view1 || !view2) return;
    
    CGRect bounds1 = view1.frame;
    CGRect bounds2 = view2.frame;
    CGRect unionRect = CGRectUnion(bounds1, bounds2);
    
    // 繪製外接矩形邊框
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGContextSetLineWidth(context, 2.0);
    CGContextStrokeRect(context, unionRect);
    
    // 可選:半透明填充
    CGContextSetFillColorWithColor(context, [[UIColor redColor] colorWithAlphaComponent:0.2].CGColor);
    CGContextFillRect(context, unionRect);
}

關鍵 API

函數作用
CGRectUnion(r1, r2)返回包含 r1 和 r2 的最小矩形 (并集)
CGRectIntersection(r1, r2)返回 r1 和 r2 的交集矩形 (可能為 CGRectNull)
CGRectContainsRect(r1, r2)判斷 r1 是否完全包含 r2
convertRect:fromView:跨視圖層級轉換座標系,**跨層級計算必須調用**

常見坑點

  • 座標系不一致:兩個 View 若不在同一 superview,直接用 frame 計算會出錯。必須用 convertRect:toView: 或 convertRect:fromView: 統一到同一座標系 (通常是共同祖先或 window)。
  • frame vs bounds:frame 是在父視圖座標系中的位置;bounds 是自身座標系。計算相對位置用 frame (轉換後)。
  • 旋轉/縮放:若 View 有 transform (旋轉、縮放),frame 可能不準確,需用 layer.bounds 配合 convertRect:fromLayer: 或計算四個頂點投影后取極值。

進階:任意多個 View 的外接矩形


- (CGRect)boundingRectOfViews:(NSArray *)views inView:(UIView *)referenceView {
    CGRect unionRect = CGRectNull;
    for (UIView *v in views) {
        CGRect converted = [referenceView convertRect:v.frame fromView:v.superview];
        if (CGRectIsNull(unionRect)) {
            unionRect = converted;
        } else {
            unionRect = CGRectUnion(unionRect, converted);
        }
    }
    return unionRect;
}

掌握 CGRectUnion、convertRect、座標系統一,即可靈活處理各類視圖幾何關係計算。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved