有没有办法将UIView保存到png而不捕获整个屏幕

时间:2011-10-12 12:31:01

标签: iphone objective-c ios cocoa-touch uiview

我要做的是保存一个UIView,它接收用户输入作为图纸,并保存图形,没有背景,这样作为应用程序中的设置,用户可以更改他们的背景图像借鉴。

我已经找到了许多用于执行屏幕捕获的代码,但没有任何关于只保存单个UIView的内容。

有什么建议吗?

4 个答案:

答案 0 :(得分:2)

您可以查看this post,这正是您所寻找的。 无论如何,这是您需要的代码。

UIView *view = ...;
CGSize size = [view bounds].size;
UIGraphicsBeginImageContext(size);
[[view layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

答案 1 :(得分: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

答案 2 :(得分: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];

答案 3 :(得分:0)

这应该只捕获视图:

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