问题
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.
回答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.
来源:https://stackoverflow.com/questions/17153356/combine-all-uilabels-with-proper-origins-into-a-uiimage