9

I Wanted to render a UIView into a CGContextRef

-(void)methodName:(CGContextRef)ctx {
    UIView *someView = [[UIView alloc] init];

    MagicalFunction(ctx, someView);
}

So, the MagicalFunction here is supposed to render the UIView(may be its layer) into current context.

How do I do that?

Thanks in advance!

aroth
  • 54,026
  • 20
  • 135
  • 176
SPatil
  • 1,003
  • 8
  • 13

1 Answers1

16

How about the renderInContext method of CALayer?

-(void)methodName:(CGContextRef)ctx {
    UIView *someView = [[UIView alloc] init];
    [someView.layer renderInContext:ctx];
}

EDIT: As noted in the comment, due to a difference in origins in the two coordinate systems involved in the process, the layer will be rendered upside-down. To compensate, you just need to flip the context vertically. This is technically done with a scale and translation transformation, which can be combined in a single matrix transformation:

-(void)methodName:(CGContextRef)ctx {
    UIView *someView = [[UIView alloc] init];
    CGAffineTransform verticalFlip = CGAffineTransformMake(1, 0, 0, -1, 0, someView.frame.size.height);
    CGContextConcatCTM(ctx, verticalFlip);
    [someView.layer renderInContext:ctx];
}
Matt Wilding
  • 20,115
  • 3
  • 67
  • 95
  • Thanks that worked! But the views are rendered upside down! Any suggestions? – SPatil Feb 19 '11 at 06:56
  • do you know how to move the someView.layer before it gets rendered? For example I have a long view I need toi plit up over several pages so I will need to adjust my view before rendering it to the second page. – Slee Jun 29 '11 at 21:06
  • @PsychoDad, this method is independent of `drawRect`. If you have overridden `drawRect` to do some custom drawing in a view, it will be rendered into the context as-is. – Matt Wilding Oct 13 '11 at 21:26