Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

iphone - Howe to capture UIView top UIView

i have UIView which displays the Graph..now I need to capture it to the UIImage and I googled it and got the below code.but if i use this in my code its not work.even if I use breakpoint compiler does not reach to this.I am using this in my UIView .where I am going wrong?

+ (UIImage *) imageWithView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return img;
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can take a screenshot of any view or whole screen of the iPhone app with below method

- (UIImage *)captureView {

//hide controls if needed
CGRect rect = [self.view bounds];

    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self.view.layer renderInContext:context];   
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;

}

And call it like bellow...

UIImage *tempImageSave=[self captureView];

and you can also save this image with this bellow line for photo album..

UIImageWriteToSavedPhotosAlbum(tempImageSave,nil,nil,nil);

and you can also save this image with this bellow line for Document Directory..

NSData *imageData = UIImagePNGRepresentation(tempImageSave);
NSFileManager *fileMan = [NSFileManager defaultManager];

NSString *fileName = [NSString stringWithFormat:@"%d.png",1];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
[fileMan createFileAtPath:pdfFileName contents:imageData attributes:nil];

If the view contains the layer images or some graphics related data then use below method.

-(UIImage *)convertViewToImage:(UIView *)viewTemp
{
    UIGraphicsBeginImageContext(viewTemp.bounds.size);
    [viewTemp drawViewHierarchyInRect:viewTemp.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;

}

And use this method like below.

UIImage *tempImageSave = [self convertViewToImage:yourView];

I hope this helpful for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...