使用核心图形和图层蒙版裁剪UIImage

时间:2015-04-13 20:56:54

标签: ios objective-c uiimageview uiimage

我一直在关注这个问题来裁剪一个与IBOutlet连接的UIImageView和一个图层蒙版,这是我跟随How to crop image inside the circle in UIImageView in iOS的问题和答案。但现在我想知道如何在没有向用户显示UIImageView的情况下完成此操作。 (因此,与IBOutlet无关)。我评论了帖子,用户说使用核心图形裁剪图像而不连接它。我不知道怎么做?所以我想知道如何将裁剪应用于具有核心Core Graphics的UIImage或UIImageView?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

例如,您可以执行以下操作,创建位图上下文,添加剪切路径,将图像绘制到该上下文中,然后从该上下文中提取图像:

NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"jpg"];
UIImage *image = [UIImage imageWithContentsOfFile:path];

size_t width = image.size.width, height = image.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = (CGBitmapInfo)kCGImageAlphaPremultipliedLast;
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 4 * width, colorSpace, bitmapInfo);

CGRect rect = ...
CGContextAddEllipseInRect(context, rect);
CGContextClip(context);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), image.CGImage);

CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage *final = [UIImage imageWithCGImage:imageRef];

NSData *data = UIImagePNGRepresentation(final);

NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *savePath      = [documentsPath stringByAppendingPathComponent:@"final.png"];

[data writeToFile:savePath atomically:YES];

CGColorSpaceRelease(colorSpace);
CGImageRelease(imageRef);
CGContextRelease(context);

有关详细信息,请参阅Quartz 2D Programming Guide。或者参考CGContext Reference