开发者

Is there any way to save a UIView to png without capturing the whole screen

开发者 https://www.devze.com 2023-04-13 00:24 出处:网络
What I\'m trying to do is save a UIView that receives user input as drawings, and save the drawing only, without the background, that way as a setting in the app, the user can change out the backgroun

What I'm trying to do is save a UIView that receives user input as drawings, and save the drawing only, without the background, that way as a setting in the app, the user can change out the background images 开发者_开发知识库they are drawing on.

I've found lots of code for doing screen captures, but nothing on saving just a single UIView.

Any suggestions?


You can take a look to this post, it's just what you are looking for. Anyway, this is the code you need.

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


This is category for 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


This should capture only the view:

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


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

精彩评论

暂无评论...
验证码 换一张
取 消