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

iOS 圖片裁剪後旋轉問題:保持原始方向與縮放比例

     編輯:程式設計綜合問答

問題現象

使用 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: 構造最終圖片,可完美解決旋轉異常問題。

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