Combine all UILabels (with proper origins) into a UIImage

烂漫一生 提交于 2019-12-25 10:29:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!