使用 CGContextDrawImage 裁剪圖片後,顯示在 UIImageView 中出現向左旋轉 90 度的情況,且無法通過旋轉修正。
imageOrientation 屬性scale 縮放因子UIGraphicsGetImageFromCurrentImageContext() 生成的圖片丟失元數據- (UIImage *)cropImage:(UIImage *)imageToCrop toRect:(CGRect)rect {
// 應用視圖變換獲取實際裁剪區域
CGRect newRect = CGRectApplyAffineTransform(rect, imageViewToCrop.transform);
UIGraphicsBeginImageContextWithOptions(newRect.size, NO, imageToCrop.scale);
CGContextRef context = UIGraphicsGetCurrentContext();
// 設置裁剪區域
CGRect clippedRect = CGRectMake(0, 0, rect.size.width, rect.size.height);
CGContextClipToRect(context, clippedRect);
// 繪製圖片(注意坐標系轉換)
CGContextDrawImage(context, newRect, imageToCrop.CGImage);
// 關鍵:保留原圖的 scale 和 orientation
CGImageRef croppedRef = CGBitmapContextCreateImage(context);
UIImage *cropped = [UIImage imageWithCGImage:croppedRef
scale:imageToCrop.scale
orientation:imageToCrop.imageOrientation];
CGImageRelease(croppedRef);
UIGraphicsEndImageContext();
return cropped;
}
| 參數 | 作用 |
|---|---|
imageToCrop.scale | 保持 Retina 屏幕下的像素密度 |
imageToCrop.imageOrientation | 保留 EXIF 方向信息(如 Up、Down、Left、Right) |
UIGraphicsBeginImageContextWithOptions | 支持縮放因子,避免模糊 |
裁剪圖片時必須顯式保留 scale 和 imageOrientation,使用 imageWithCGImage:scale:orientation: 構造最終圖片,可完美解決旋轉異常問題。