Draw text and add to a UIImage iOS 5/6

强颜欢笑 提交于 2019-12-29 05:32:04

问题


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?


回答1:


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




回答2:


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:


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.



来源:https://stackoverflow.com/questions/12571852/draw-text-and-add-to-a-uiimage-ios-5-6

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