views:

28

answers:

1

I have a custom UIImageView class that creates thumbnails (UIImageView) and each thumbnail has a label.

The label is created by another class. The label class creates a UIImageView and a UITextView on top of it.

This is the main thumbnail class' init method:

- (id)initWithFrame:(CGRect)frame
{
    if ([super initWithFrame:frame] == nil) {
        return nil;
    }

 CGRect myFrame = CGRectMake(0, 0, 100, 100);
 myLabel = [[myLabelClass alloc] initWithFrame: myFrame]; //myLabelClass is a UIImageView based class
 [myLabel setCenter:CGPointMake(50, 50)];
 [self addSubview: myLabel];

  return self;
}

The label class just creates a UIImageView and a UITextView and put text on it.

So, I have this

 MAIN VIEW CONTROLLER   |   
                        |___ UIImageView WITH LABEL
                                                |
                                                |____ label background (UIView)
                                                |____ UITEXTVIEW (text)

Now I want to write the contents of all these 3 components to a quartz context.

I need to write using drawInRect, because I need to write the full object to a precise location.

I expected object.layer.contents to be the image equivalent to these 3 "layers" flattened, in other words, the object's image, the label background and the label text, as it would if I created these 3 objects in Photoshop and flatten the composition.

I also expect thumbnail.myLabel.layer.contents to contains the rendered contents of the UITextView over the label background.

The problem is that when I use

UIImage *myImage = [UIImage imageWithCGImage:thumbnail.myLabel.layer.contents];
[myImage drawInRect:CGRectMake(0, 0, 100, 100)];

I get nothing.

How can I obtain a "flattened" image resultant to the full object (including its subviews)?

thanks

+2  A: 

CALayer contents is only valid if you set it. Try creating a context with UIGraphicsBeginImageContext and using CALayer renderInContext to create the image. I use something like this as a category of UIView:

-(UIImage *) asImage {
    UIImage     *result = nil;

    UIGraphicsBeginImageContext( [self bounds].size );
    [[self layer] renderInContext:UIGraphicsGetCurrentContext()];
    result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return result;
}
drawnonward
man, you are a genius! THANKS!!!!! The easiest way is obviously rendering inside the class, but I was not seeing it! :-)
Digital Robot