我想要做的是保存一个接收用户输入作为绘画的UIView,只保存绘画而不包括背景,这样在应用程序中作为设置,用户可以更改他们正在绘制的背景图像。我找到了很多关于屏幕截图的代码,但没有关于保存单个UIView的内容。你有什么建议吗?
UIView *view = ...;
CGSize size = [view bounds].size;
UIGraphicsBeginImageContext(size);
[[view layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIView
的类别:@interface UIView(Image)
- (UIImage*)image;
@end
#import "UIView+Image.h"
#import <QuartzCore/QuartzCore.h>
@implementation UIView(Image)
- (UIImage *)image {
CGSize imageSize = self.bounds.size;
UIGraphicsBeginImageContext(imageSize);
CGContextRef imageContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(imageContext, 0.0, imageSize.height);
CGContextScaleCTM(imageContext, 1.0, -1.0);
//for (CALayer* layer in self.layer.sublayers) {
// [layer renderInContext: imageContext];
//}
[self.layer renderInContext: imageContext];
UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return viewImage;
}
@end
CGSize imgsize = self.view.bounds;
UIGraphicsBeginImageContext(imgsize);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *NewImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImageJPEGRepresentation(NewImg,1);
NSString *fullPath = @""; //Path of Document directory where u wish to save the image.
BOOL success = [mediaData writeToFile:fullPath atomically:YES];
这应该只捕获视图:
UIGraphicsBeginImageContext(someView.bounds.size);
[someView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();