0

I am using these functions to draw text over an image:

char* text = (char *)[text1 cStringUsingEncoding:NSASCIIStringEncoding];
CGContextSelectFont(context, "Helvetica", fontSize, kCGEncodingMacRoman);
CGContextSetTextDrawingMode(context, kCGTextFill);
CGContextSetRGBFillColor(context, 0.0, 0.1, 0.1, 1);
CGContextShowTextAtPoint(context, 5, 20, text, strlen(text));

It works fine, except when I have character such as "ü", "ö", "ä" etc etc with strlen - it will cause a crash. So I tried to get the length of a string by using this before this line

char* text = (char *)[text cStringUsingEncoding:NSASCIIStringEncoding];
by doing this:
int length = [text length];
and then replace strlen(text) with length.

it doesn't cause a crash, but no text is drawn. I think the culprit here is the characters. I have tried both

kCGEncodingMacRoman
kCGEncodingFontSpecific

but nothing helped. Can you me with this? Thanks.

UPDATED: @Martin R:

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, 90.0f, 90.0f, 8, 4 * 90.0f, colorSpace,     kCGImageAlphaPremultipliedFirst);
CGContextDrawImage(context, CGRectMake(0, 0, 90.0f, 90.0f), img.CGImage);

CGContextSetTextDrawingMode(context, kCGTextFill);
CGContextSetRGBFillColor(context, 0.8, 0.1, 0.1, 1);
[text1 drawAtPoint:(CGPoint){5, 20} withFont:[UIFont fontWithName:@"Helvetica" size:10.0f]];
CGImageRef finalImage = CGBitmapContextCreateImage(context);

CGContextRelease(context);
CGColorSpaceRelease(colorSpace);

UIImage *image = [UIImage imageWithCGImage:finalImage];
CGImageRelease(finalImage);

return image;
4

1 回答 1

1

CGContextShowTextAtPoint()根据指定的编码参数解释给定的文本,CGContextSelectFont()在您的情况下是 Mac Roman。所以你应该使用转换字符串

NSString *string = @"äöü";
const char *text = [string cStringUsingEncoding:NSMacOSRomanStringEncoding];

或者,您可以使用自动处理 Unicode 字符的drawAtPoint:withFont:方法NSString

NSString *string = @"äöü€";
[string drawAtPoint:CGPointMake(5, 20) withFont:[UIFont fontWithName:@"Helvetica" size:12]];
于 2013-07-02T11:41:04.540 回答