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

iOS 獲取 UIView 四個角座標:用 convertRect 簡單高效

     編輯:程式設計綜合問答

需求

取得 UIView 在指定座標系(如父視圖或螢幕)中的四個頂點 CGPoint。

最佳方法:convertRect:fromView:

CGRect rect = [self.view convertRect:self.view.frame fromView:nil]; // 轉換到 self.view 座標系
// 或轉換到螢幕座標系
CGRect screenRect = [self.view convertRect:self.view.bounds toView:nil];

計算四個角

CGPoint topLeft     = rect.origin;
CGPoint topRight    = CGPointMake(rect.origin.x + rect.size.width, rect.origin.y);
CGPoint bottomLeft  = CGPointMake(rect.origin.x, rect.origin.y + rect.size.height);
CGPoint bottomRight = CGPointMake(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);

優點

  • 一行取得位置與大小,自動處理視圖層級轉換
  • 避免逐點 convertPoint: 繁瑣且易錯
  • fromView:nil 表示轉換到視窗(螢幕)座標系

Swift 版本

let rect = view.convert(view.bounds, to: nil)
let corners = [
    rect.origin,
    CGPoint(x: rect.maxX, y: rect.minY),
    CGPoint(x: rect.minX, y: rect.maxY),
    CGPoint(x: rect.maxX, y: rect.maxY)
]
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved