Write multiline over an image
text1
is a very long string so, I want multiline support.
What do I have to do for this?
int w = img.size.width;
int h = img.size.height;
CGColorSpaceRef colorSpace= CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4*w, colorSpace, kCGImageAlphaPremultipliedFirst)开发者_运维知识库;
CGContextDrawImage(context, CGRectMake(0,0, w, h), img.CGImage);
CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1);
char* text = (char *)[text1 cStringUsingEncoding:NSASCIIStringEncoding];
CGContextSelectFont(context, "Arial", 18, kCGEncodingMacRoman);
CGContextSetTextDrawingMode(context, kCGTextFill);
CGContextSetRGBFillColor(context, 255,255,255,1);
//CGContextSetTextMatrix(context, CGAffineTransformMakeRotation(-M_PI/4));;
CGContextShowTextAtPoint(context, w/3 + 10, 5, text, strlen(text));
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIImage imageWithCGImage:imageMasked];
If you don't mind using UIKit methods instead of CGContext methods to draw your text, you can just use drawInRect:withFont:lineBreakMode:
to draw the text, which will handle wrapping for you. Note that you can use UIGraphicsPushContext
and UIGraphicsPopContext
to go from your existing CGGraphicsRef to the UIKit context, and if you are targeting iOS earler than 4.0 you have to do the UIKit drawing on the main thread.
I assume you want to support multiline.
Then you can always use this:
CGSize size = [text sizeWithFont:[UIFont fontWithName:@"Georgia-Bold" size:18.0]
constrainedToSize:CGSizeMake(240.0, 480.0) lineBreakMode:UILineBreakModeWordWrap];
Assign the width and height (in :CGSizeMake(240.0, 480.0)
), font type and size, and then assign this size for your text1.frame
.
You will get your size according to your string and your text will be adjusted there.
精彩评论