iOS UIImage 裁剪:使用 Core Graphics 获取最清晰的裁剪图片
可以使用 Core Graphics 框架来实现对 UIImage 对象的裁剪,具体步骤如下:
- 创建一个基于位图的上下文,大小与裁剪区域一致,并设置缩放因子为图片的比例因子。
UIGraphicsBeginImageContextWithOptions(cropRect.size, NO, image.scale);
- 将图片绘制到上下文中,并指定裁剪区域。
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, -cropRect.origin.x, -cropRect.origin.y);
[image drawAtPoint:CGPointZero];
- 从上下文中获取裁剪后的图片。
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
- 关闭上下文。
UIGraphicsEndImageContext();
完整的代码示例如下:
CGRect cropRect = CGRectMake(x, y, width, height);
UIGraphicsBeginImageContextWithOptions(cropRect.size, NO, image.scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, -cropRect.origin.x, -cropRect.origin.y);
[image drawAtPoint:CGPointZero];
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
这样就可以得到一个清晰的裁剪后的 UIImage 对象。
原文地址: http://www.cveoy.top/t/topic/fl9k 著作权归作者所有。请勿转载和采集!