How to convert text to Image on iOS?

前端 未结 7 2261
庸人自扰
庸人自扰 2020-12-07 18:10

I am trying to write a function to convert the textfield text to an image (example). I have tried to search for an example, most of the sample also is overwrite text on imag

相关标签:
7条回答
  • 2020-12-07 18:49

    You could try creating your own custom UIView subclass, drawing an NSString on it (your text), then converting that to a UIImage. You can draw text on a UIView only in the -drawRect: method. Here is an idea for your subclass.

    @interface TextView : UIView {
        NSString *_text;
    }
    - (id)initWithFrame:(CGRect)frame andText:(NSString *)text;
    @end
    
    @implementation TextView
    - (id)initWithFrame:(CGRect)frame andText:(NSString *)text
    {
        if (self = [super initWithFrame:frame]) {
            _text = text;
        }
        [self setNeedsDisplay]; // calls the -drawRect method
        return self;
    }
    
    - (void)drawRect:(CGRect)rect
    {
        [_text drawAtPoint:/* location of text*/ 
            withAttributes:/* style    of text*/];
    }
    

    More information about drawing NSStrings can be found here. Once you have this view with your text on it, convert it to a UIImage with this technique.

    0 讨论(0)
提交回复
热议问题