2012-09-05 42 views
5
- (UIImage *)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect 
{ 
    CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect); 
    UIImage *cropped = [UIImage imageWithCGImage:imageRef]; 
    CGImageRelease(imageRef); 
    return cropped; 
} 

我使用此代碼。請提供一些解決方法。預先感謝圖像裁剪在iOS 6.0中無法正常工作。在模擬器中正常工作。

+0

示例代碼和教程.... http://developer.apple.com/library/mac/#/legacy/mac/library/samplecode/Cropped_Image/Introduction/Intro.html http://www.icodeblog。 com/2010/10/14/working-with-uigesturerecognizers/http://stackoverflow.com/questions/7950719/how-to-crop-the-image-in-iphone http://www.samwirch.com/blog/cropping-and-resizing-images-camera-ios-and-objective -c http://mobiledevelopertips.com/graphics/how-to-crop-an-image.html – Ayaz

回答

4

CGImageCreateWithImageInRect無法正確處理圖像方向。 網絡上有很多奇怪而奇妙的裁剪技術,涉及巨型開關/案例陳述(請參閱Ayaz答案中的鏈接),但如果您停留在UIKit級別並僅使用UIImage本身的方法來執行繪圖,所有細節的細節都照顧你。

下面的方法是,你可以得到儘可能簡單,我所遇到的所有情況都適用:

- (UIImage *)imageByCropping:(UIImage *)image toRect:(CGRect)rect 
{ 
    if (UIGraphicsBeginImageContextWithOptions) { 
     UIGraphicsBeginImageContextWithOptions(rect.size, 
               /* opaque */ NO, 
               /* scaling factor */ 0.0); 
    } else { 
     UIGraphicsBeginImageContext(rect.size); 
    } 

    // stick to methods on UIImage so that orientation etc. are automatically 
    // dealt with for us 
    [image drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)]; 

    UIImage *result = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return result; 
} 

您可能需要改變opaque參數的值,如果你不需要的透明度。

+0

感謝您的回覆。這也適用於我的舊源代碼。我的問題是裁剪圖像變得更加模糊,這個問題只發生在設備上。任何其他想法都會幫助我。 – Mani

+0

這聽起來像是視網膜鱗片的問題。我發佈的代碼將在結果圖像中使用屏幕的比例尺,但您需要注意您傳入的裁剪矩形是以點爲單位的,而不是像素。 –

+0

如何傳遞像素。請你解釋一下,不理解你的答案。如何處理視網膜顯示作物問題。 – Mani

相關問題