在 iOS 開發中測試 Retina 螢幕適配時,常見困惑:載入 @2x 圖片後,UIImage.size 返回的邏輯尺寸(points)與非 Retina 圖片相同,只有 scale 屬性變為 2.0。這其實是 Apple 設計的核心機制。
UIImage *myImage = [UIImage imageNamed:@"image1.png"];
// 自動載入 image1@2x.png (若在 Retina 設備)
CGFloat imageWidth = myImage.size.width; // 320
CGFloat imageHeight = myImage.size.height; // 57
NSLog(@"image %f %f", imageWidth, imageHeight);
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width; // 320
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height; // 568
NSLog(@"screen %f %f", screenWidth, screenHeight);
// 關鍵屬性
NSLog(@"scale %f", myImage.scale); // Retina 設備輸出 2.0
Pixels = Points × Scale// 邏輯尺寸(Points)- 佈局計算使用
@property (readonly) CGSize size; // 如 320x57
// 縮放比例 - 渲染時使用
@property (readonly) CGFloat scale; // 1.0 (標準) / 2.0 (Retina) / 3.0 (Plus 系列)
// 物理像素尺寸 - 實際圖檔像素
// 計算方式:size.width * scale, size.height * scale
// 如:320 * 2.0 = 640px, 57 * 2.0 = 114px
CGRect、CGPoint、CGSize 都用 PointsimageNamed: 根據螢幕 scale 自動載入 @2x/@3x 圖片size、frame、bounds)@1x、@2x、@3x 三套圖片資源pixelWidth = image.size.width * image.scaleUIGraphicsBeginImageContextWithOptions) 設置正確 scale// 檢查 scale 屬性
if (myImage.scale >= 2.0) {
NSLog(@"Retina 圖片已載入");
}
// 或檢查螢幕 scale
CGFloat screenScale = [UIScreen mainScreen].scale;
NSLog(@"螢幕 scale: %f", screenScale); // 2.0 或 3.0