How to draw an NSString with an specific height on to an perfectly matching bitmap?

时光总嘲笑我的痴心妄想 提交于 2020-01-05 10:04:04

问题


I have an NSString like @"Hello World" and want to convert that into an bitmap with exactly 20 pixels height. The width of the bitmap should match the width of the text.

I know there are some NSString UIKit additions that can draw text, but I don't know how to draw the text with an bounding box of exactly 20 pixels height (text fits perfectly into this height) into an bitmap that has the perfect size to carry the text?

Is there an easy way to do this?

This must also work with Chinese, Japanese, Russian and Arabic style letters. Maybe I could just put the text in a UILabel and then get it's content bitmap somehow. But the content bitmap of the UILabel would be either too short, or too long in width.

Maybe I must first ask the text itself how big it would be at a certain font size (= height?), and then manually create a bitmap with the exact dimensions needed, and draw the text on this bitmap?


回答1:


The way I was told to do it for Cocoa at this question works, and despite the premature optimisation part of my brain doing a wobbly it isn't too slow.

Once you've drawn the text to your satisfaction, you can use this method to obtain an image representation of the view.



来源:https://stackoverflow.com/questions/3776632/how-to-draw-an-nsstring-with-an-specific-height-on-to-an-perfectly-matching-bitm

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