「兩個 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;
}
- (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);
}
| 函數 | 作用 |
|---|---|
CGRectUnion(r1, r2) | 返回包含 r1 和 r2 的最小矩形 (并集) |
CGRectIntersection(r1, r2) | 返回 r1 和 r2 的交集矩形 (可能為 CGRectNull) |
CGRectContainsRect(r1, r2) | 判斷 r1 是否完全包含 r2 |
convertRect:fromView: | 跨視圖層級轉換座標系,**跨層級計算必須調用** |
superview,直接用 frame 計算會出錯。必須用 convertRect:toView: 或 convertRect:fromView: 統一到同一座標系 (通常是共同祖先或 window)。frame 是在父視圖座標系中的位置;bounds 是自身座標系。計算相對位置用 frame (轉換後)。transform (旋轉、縮放),frame 可能不準確,需用 layer.bounds 配合 convertRect:fromLayer: 或計算四個頂點投影后取極值。
- (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、座標系統一,即可靈活處理各類視圖幾何關係計算。