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
參數的值,如果你不需要的透明度。
示例代碼和教程.... 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