2013-05-17 90 views
1

我有一個UIImage是從一個透明的PNG(500px乘500px)讀取。在圖像的某個地方,有一張我想要裁剪並保存爲獨立UIImage的圖片。我還想根據新裁剪的矩形左側和頂部有多少透明像素來存儲X和Y座標。核心圖形 - 如何從UIImage中裁剪非透明像素?

我能夠使用此代碼裁剪圖像:

- (UIImage *)cropImage:(UIImage *)image atRect:(CGRect)rect 
{ 
    double scale = image.scale; 
    CGRect scaledRect = CGRectMake(rect.origin.x*scale,rect.origin.y*scale,rect.size.width*scale,rect.size.height*scale); 

    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], scaledRect); 
    UIImage *cropped = [UIImage imageWithCGImage:imageRef scale:scale orientation:image.imageOrientation]; 
    CGImageRelease(imageRef); 
    return cropped; 
} 

裏面居然切斷透明像素的頂部和左:S(這將是巨大的,如果我能對作物的像素正確和底部!)。然後它將圖像的其餘部分調整爲我指定的矩形。不幸的是,雖然我需要剪切一張位於圖像中間的圖片,但我需要的尺寸能夠變爲動態。

現在已經掙扎了好幾個小時了。有任何想法嗎?

+0

你描述的不是CGImageCreateWithImageInRect'是如何'記錄工作,是(根據文檔)功能不能擴展任何東西。你應該把這些代碼分解成一個最小的測試應用程序,如果你仍然可以重現這個問題,請[提交bug](https://bugreport.apple.com/)。 –

回答

3

要裁剪圖像,請將其繪製到較小的圖形上下文中。

例如,假設你有一個600×600的圖像。假設您想從四面裁剪200個像素。這留下了200x200的矩形。

所以,你會做一個200x200的圖形上下文,使用UIGraphicsBeginImageContextWithOptions。然後,您將使用drawAtPoint:將圖像繪製到該圖像中,並在點(-200,-200)處繪製。如果你仔細想一想,你會發現這個偏移量會導致從原始中間的200x200被拉入上下文的實際範圍。因此,您已經在四面裁剪了200像素的圖像,這正是我們想要做的。

因此,這裏是一個廣義的版本,假設我們知道量從左邊裁剪,右,上,下:

UIImage* original = [UIImage imageNamed:@"original.png"]; 
CGSize sz = [original size]; 
CGFloat cropLeft = ...; 
CGFloat cropRight = ...; 
CGFloat cropTop = ...; 
CGFloat cropBottom = ...; 
UIGraphicsBeginImageContextWithOptions(
    CGSizeMake(sz.width - cropLeft - cropRight, sz.height - cropTop - cropBottom), 
    NO, 0); 
[original drawAtPoint:CGPointMake(-cropLeft, -cropTop)]; 
UIImage* cropped = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

之後,cropped是你裁剪圖像。

+0

在本書的這一部分中有一個相當類似的例子:http://www.apeth.com/iOSBook/ch15.html#_uiimage_drawing – matt