使用UIImagePNGRepresentation保存UIImage不保留我的图层修改

cth*_*ase 2 objective-c calayer uiimage ios

我正在从NSData加载图像.原始图像是作为JPG创建的.当我尝试设置角半径并保存到磁盘时,我正在丢失我所做的更改.我将PNG保存为磁盘,因为我认为将在需要保留的图层上创建alpha通道.

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:data]];
[imageView.layer setMasksToBounds:YES];
[imageView.layer setCornerRadius:10.0f];
data = UIImagePNGRepresentation(imageView.image);
// save data to file with .png extension
Run Code Online (Sandbox Code Playgroud)

问题是当我将图像从文件系统重新加载回UIImage时,角半径不可见.

小智 8

CGContext可以采用"截图".

UIGraphicsBeginImageContext(self.frame.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// Now I use the "screenshot"
NSString *path = [NSHomeDirectory() stringByAppendingString:@"/image.jpg"];
if ([UIImageJPEGRepresentation(image, 1) writeToFile:path atomically:YES]) {
    NSLog(@"save ok");
}
else {
    NSLog(@"save failed");
}
Run Code Online (Sandbox Code Playgroud)