Domanda

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;
È stato utile?

Soluzione

CGContextShowTextAtPoint() interprets the given text according to the specified encoding parameter of CGContextSelectFont(), which is Mac Roman in your case. So you should convert the string using

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

Alternatively, you could use the drawAtPoint:withFont: method of NSString, which handles Unicode characters automatically:

NSString *string = @"äöü€";
[string drawAtPoint:CGPointMake(5, 20) withFont:[UIFont fontWithName:@"Helvetica" size:12]];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top