- (UIImage *)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return cropped;
}
Run Code Online (Sandbox Code Playgroud)
我正在使用此代码.请给出一些解决方案.谢谢
CGImageCreateWithImageInRect
无法正确处理图像方向。网上有许多奇怪而美妙的裁剪技术,涉及巨大的 switch/case 语句(请参阅 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;
}
Run Code Online (Sandbox Code Playgroud)
opaque
如果不需要透明度,您可能需要更改参数的值。
归档时间: |
|
查看次数: |
1598 次 |
最近记录: |