Crop UIImage with Core Graphics and Layer Mask [duplicate]

守給你的承諾、 提交于 2019-12-12 02:46:11

问题


I have been following this SO question to crop an UIImageView that is connected with IBOutlet with a Layer Mask, here is the question and answer I was following How to crop image inside the circle in UIImageView in iOS. But now I am wondering how this could be done without have a UIImageView shown to the user. (So one that is not connected to IBOutlet). I commented on the post and the user said to use core graphics to crop the image without having it connected. Im not sure how to do this? So I am wondering how to apply a crop to a UIImage or UIImageView with core Core Graphics?

Thanks for the help in advance.


回答1:


You could, for example, do something like the following, which creates a bitmap context, adds a clipping path, draws an image into that context, and then extracts the image back out of that context:

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);

For more information, see the Quartz 2D Programming Guide. Or refer to the CGContext Reference.



来源:https://stackoverflow.com/questions/29614956/crop-uiimage-with-core-graphics-and-layer-mask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!