Draw text and add to a UIImage iOS 5/6

2019-01-23 20:40发布

I have a textbox, where i want the written text to be added to a UIImage.

How can i draw NSString to a UIImage?

I´ve searched, and found lots of examples, but non of them works. Xcode just gives me lots of errors.

Simply put, i want to draw a NSString to a UIimage. The UIImage should be the same size as a predefined UIImageView, and be placed in center.

Any ideas?

3条回答
何必那么认真
2楼-- · 2019-01-23 21:05

UIImage is not a subview of UIView, so you cant add a subview to it. Also NSString is not a subview of UIView. If you want to show things on the screen, they should inherit from UIView.

So try this:

Create a UIImageView - set its image property to be your UIImage instance.

Create a UILabel - set its text property to your NSString.

Add the UILabel as a subview of your UIImageView.

and finally add your UIImageView to your current view controllers view.

查看更多
我命由我不由天
3楼-- · 2019-01-23 21:08

Emm, here is some thoughts. I think that one simple way is like this :

  1. Put aUIImageView on aView;
  2. Add aUITextView on aView;
  3. Get ScreenShot from aView;

This may works fine.

Also, this may come with a problem that screenshot may be not clear. Then, After step1 and step2, we may get new image by UIGraphics. (With here, we already know position where text should be on image and this should be ok.)

PS: Some image may not have some attribution like CGImage and CGImage is needed for this. So, transform it.

查看更多
Rolldiameter
4楼-- · 2019-01-23 21:24

i think solution is here..i have used this method in one of my application here lbltext is the object of my label. this method creates new image with given text & return the object of new image with text.

-(UIImage *) drawText:(NSString*) text inImage:(UIImage*)image atPoint:(CGPoint)point 
{
    UIFont *font = lblText.font;
    UIGraphicsBeginImageContext(iv.frame.size);
    [image drawInRect:CGRectMake(0,0,iv.frame.size.width,iv.frame.size.height)];
    CGRect rect = CGRectMake(point.x,point.y,lblText.frame.size.width, lblText.frame.size.height);
    [lblText.textColor set];
    [text drawInRect:CGRectIntegral(rect) withFont:font]; 
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

in your below comment you have passed iv.center as a point.. try manualy like this

CGPoint point;
point.x=30; // dynamicaly just for example lblText.frame.origin.x;
point.y=40; //lblText.frame.origin.y;

you have to call above method like this...

UIImage *img = [self drawText:@"Test String" inImage:originalImage atPoint:point];

here,img is another instace of UIImage for storing new image with text...after calling this method use img imager for your further use..

for example...

[newimageviewObj setImage:img];

i hope this will help you

查看更多
登录 后发表回答