有没有方法将UIView保存为PNG格式而不必捕捉整个屏幕?

3
我想要做的是保存一个接收用户输入作为绘画的UIView,只保存绘画而不包括背景,这样在应用程序中作为设置,用户可以更改他们正在绘制的背景图像。我找到了很多关于屏幕截图的代码,但没有关于保存单个UIView的内容。你有什么建议吗?

谢谢你们的迅速回答,我会尝试它们并给第一个有效的答案点赞和采纳。 - Travis
很好的发现,Bavarious。 我的意思是cocoa-touch。 - Travis
4个回答

2
你可以查看这篇帖子,它正是你所需要的。无论如何,这就是你需要的代码。
UIView *view = ...;
CGSize size = [view bounds].size;
UIGraphicsBeginImageContext(size);
[[view layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

1
这是关于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

0
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];

0

这应该只捕获视图:

UIGraphicsBeginImageContext(someView.bounds.size);
[someView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接