简体   繁体   English

将UIView转换为UIImage而不先显示UIView?

[英]Convert UIView to UIImage without first displaying the UIView?

I am looking for a way to present two rows of text, each differently sized and colored, within each UITabBarItem of my app. 我正在寻找一种在我的应用程序的每个UITabBarItem中呈现两行文本的方法,每行文本的大小和颜色都不同。 For this reason, I am looking for a way to make easy custom TabBarItems whose text can be dynamically updated within the app. 基于这个原因,我正在寻找一种使自定义TabBarItems变得容易的方法,其文本可以在应用程序中动态更新。 For example, one button could tell the user "Menu" up top and below tell the user how many "votes" she has left for the day (a number that will change during the session in response to user actions). 例如,一个按钮可以在顶部和底部告诉用户“菜单”,并在一天之内告诉用户她剩下多少“票”(该数字将在会话期间响应用户操作而改变)。

I thought an obvious approach would be to make UITabBarItem custom images out of UIViews. 我认为一种明显的方法是从UIViews中制作UITabBarItem自定义图像。 I hoped this could be an easy and low-overhead way to include custom tab bar buttons with dynamic text content. 我希望这是一种包含动态文本内容的自定义标签栏按钮的简便且开销较低的方法。 But I haven't been able to find a method to convert a non-presented UIView into a UIImage. 但是我一直找不到能够将未显示的UIView转换为UIImage的方法。 How can I do this? 我怎样才能做到这一点?

There are many posts on converting already presented UIViews to images listed below, but I haven't been able to find any on converting the view without presenting it: 关于将已经呈现的UIViews转换为下面列出的图像,有很多文章,但是在不显示视图的情况下,我找不到任何相关内容:

If this is simply not possible, I would also appreciate any recommendations for easily (coding wise and computationally) generating custom buttons with dynamically generated text. 如果这根本不可能,那么我也将对通过动态生成的文本轻松地(自定义和计算方式)生成自定义按钮的任何建议表示赞赏。 Thank you for any suggestions! 感谢您的任何建议!

You can avoid using UIView and draw UIImage like this. 您可以避免使用UIView并像这样绘制UIImage。
If you need more fency text try NSAttributedString . 如果您需要更多精美的文字,请尝试NSAttributedString

UIGraphicsBeginImageContext(CGRect(0,0,200,200);

[[UIColor redColor] setFill];
UIFont *font = [UIFont systemFontOfSize:18.0];
NSString * text = @"A text";
[text drawAtPoint:CGPointMake(0, 0) withFont: font];

UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Core graphics is very flexible in this metter so in the same way you can use 核心图形在此表中非常灵活,因此您可以以相同的方式使用
UIImage and it's methods to draw UIImage into the context UIImage及其将UIImage绘制到上下文中的方法
or CoreText framework and draw much more complicated things. CoreText框架并绘制更复杂的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM