Chandni
Chandni

Reputation: 690

convert uiview to .png image

I am working on iphone and I take the subclass of UIView and in draw rect method I am making some design. I want to convert this view in .png format.

Thanks in advance.

Upvotes: 6

Views: 6042

Answers (2)

Dhaval Panchal
Dhaval Panchal

Reputation: 2529

    UIGraphicsBeginImageContext(myView.frame.size);
    [myView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *data=UIImagePNGRepresentation(viewImage);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *strPath = [documentsDirectory stringByAppendingPathComponent:@"myimage.png"];
    [data writeToFile:strPath atomically:YES];

Upvotes: 22

Mani
Mani

Reputation: 1841

   UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
        UIGraphicsBeginImageContextWithOptions(YourView.frame.size, NO, [UIScreen mainScreen].scale);
    else
        UIGraphicsBeginImageContext(keyWindow.bounds.size);

    CGContextRef context = UIGraphicsGetCurrentContext();
    [keyWindow.layer renderInContext:context];   
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil); 
    UIGraphicsEndImageContext();

Upvotes: 1

Related Questions