0

So the app I'm working on lets users write text, and the app translate that text into separate UILabels (one UILabel that only contains the text, and another UILabel that is the same width as the text, but with a transparent color background). I want to combine all the uilabels with the UIImage in the background to create a new UIImage.

So far I have the following code, but it does not produce any tangible results and would love anyone's help with this problem:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(320, 416), NO, 0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[_imgViewFinal.layer renderInContext:ctx];
CGContextSaveGState(ctx);
for (int i = 0; i < _allLabels.count; i++) {
    UILabel *tempLabelBg = [_allBgs  objectAtIndex:i];
    CGContextTranslateCTM(ctx, tempLabelBg.frame.origin.x, tempLabelBg.frame.origin.y);
    CGContextSaveGState(ctx);
    [tempLabelBg.layer renderInContext:ctx];
    CGContextRestoreGState(ctx);

    UILabel *tempLabelText = [_allLabels objectAtIndex:i];
    [tempLabelText drawTextInRect:tempLabelText.frame];
}

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
NSData *imgData =  UIImageJPEGRepresentation(image, 1.0); 
UIImage * imagePNG = [UIImage imageWithData:imgData]; 
UIGraphicsEndImageContext();

*I know that drawTextInRect does not use the contextref I create. I'm not sure how to draw the text into the context. I don't think I'm using the CGContextSave and Restore properly either.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
liquidpenguins
  • 994
  • 1
  • 14
  • 26

1 Answers1

1
UIGraphicsBeginImageContextWithOptions(myView.bounds.size, myView.opaque, 0.0);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

where myView is the view holding whatever you want in the image (img) we're creating.. I didn't test it for Labels, but it should work fine.

DrDev
  • 452
  • 2
  • 7
  • That's perfect! Except it doesn't capture the origin of the view. What would I have to add to also capture where the uiview is? Is there something like drawTextInRect for a UIView? – liquidpenguins Jun 17 '13 at 21:41
  • Oh ok, I can just use a CGContextRef to create a new context and use CGContextTranslateCTM to provide it the UIView's origin and voila! Thank you. – liquidpenguins Jun 17 '13 at 21:49