将所有UILabel(具有适当的原点)组合成UIImage [英] Combine all UILabels (with proper origins) into a UIImage

查看:195
本文介绍了将所有UILabel(具有适当的原点)组合成UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在处理的应用程序允许用户编写文本,应用程序将该文本转换为单独的UILabel(一个仅包含文本的UILabel,另一个与文本宽度相同的UILabel,但具有透明颜色背景)。我想在背景中将所有的uilabels与UIImage结合起来创建一个新的UIImage。

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();

*我知道drawTextInRect不使用我创建的contextref。我不确定如何将文本绘制到上下文中。我不认为我正在使用CGContextSave和Restore。

*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.

推荐答案

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

UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

其中myView是我们正在创建的图像(img)中包含您想要的任何内容的视图。我没有为标签测试它,但它应该可以正常工作。

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.

这篇关于将所有UILabel(具有适当的原点)组合成UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆