iAkshay
iAkshay

Reputation: 1263

UIImage from custom UIView in Xib returning empty image with black background

Basically, I'm looking out for a way to attach custom UIView from XIB so that it can be use as link preview in UILabel. I'd choose to convert UIView into UIImage as an image can be use in NSTextAttachment which in turn can use in NSAttributedString.

I'm trying to get image from this UIView. The code is as follows :

UIView *preView = [[[NSBundle bundleForClass:[self class]] loadNibNamed:@"LinkPreview" owner:self options:nil] firstObject];

//preView contains 3 labels and 1 imageview with hardcoded values for testing 

if(preView)
{
      preView.bounds = CGRectMake(0,0,400,200);
      NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
      attachment.image = [preView snapShot];
      .
      .
}

method snapShot is defined in UIView category :

#import "UIView+Snapshot.h"
#import <QuartzCore/QuartzCore.h>

@implementation UIView (Snapshot)

-(UIImage *)snapShot
{
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0f);
    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
    UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

@end

This code returning me the empty image with black background.

Update 1 : The preView is just fine

enter image description here

Please help.

Upvotes: 0

Views: 332

Answers (1)

ibnetariq
ibnetariq

Reputation: 738

Your view has not been added to view hierarchy. Means that its not rendered yet. Therefore you are getting a black image.

Just for testing purpose, add it as as subview of your current view and then snapshot. It will surely work.

Update :

If you need to snapshot without adding it to hierarchy try this

-(UIImage *)snapShot
{
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0f);
    [self.layer renderInContext: UIGraphicsGetCurrentContext()];
    UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

reference : Screenshot of a view without displaying it

Upvotes: 0

Related Questions