简体   繁体   中英

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. For this reason, I am looking for a way to make easy custom TabBarItems whose text can be dynamically updated within the app. 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. 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. 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:

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.
If you need more fency text try 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
or CoreText framework and draw much more complicated things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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