用核心graphics和图层蒙版裁剪UIImage

我一直在跟随这个问题来裁剪一个UIImageView与IBOutlet与图层蒙板连接,这里是问题和答案我下面如何在iOS中的UIImageView中圈内裁剪图像 。 但是现在我想知道如何在没有显示给用户的UIImageView的情况下完成这个工作。 (所以没有连接到IBOutlet)。 我评论了这篇文章,用户说,使用核心graphics裁剪图像没有连接。 我不知道如何做到这一点? 所以我想知道如何将裁剪应用到具有核心Core Graphics的UIImage或UIImageView?

我在这里先向您的帮助表示感谢。

例如,你可以做下面的事情,创build一个位图上下文,添加一个剪切path,在上下文中绘制一个图像,然后将图像从该上下文中提取出来:

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参考 。