I’m just trying to overlay a text in a UIImage (using CGContext) but it doesn’t show the text I specified. In this code I’m giving as the text argument "Hello" but it shows “eÉääc”. I don’t know what’s happening I think the characters are displaced but I don’t know how to solve it.
This is my code:
UIGraphicsBeginImageContextWithOptions(image.size, YES, 0);
CGContextRef c = UIGraphicsGetCurrentContext();
[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
CGContextSetTextMatrix(c, CGAffineTransformMake(1.0, 0, 0, -1.0, 0, 0));
CGContextSelectFont(c, "ArialMT", 50, kCGEncodingFontSpecific);
CGContextSetRGBStrokeColor(c, 255, 0, 0, 1);
CGContextSetRGBFillColor(c, 255, 0, 0, 1);
CGContextSetCharacterSpacing(c, 2);
CGContextShowTextAtPoint(c,100,100, "Hello", 5);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
I’m using the Spanish Keyboard (I don’t know if this matters) and the iPad (where I’m testing the application) is in Catalan.
CGContextShowTextAtPoint()interprets the given text according to the specified encoding parameter ofCGContextSelectFont. You have chosenkCGEncodingFontSpecific, which is the font built-in encoding (whatever that might be).The only other choice is
kCGEncodingMacRoman:Then your text should display correctly, as long as you use only characters from the ASCII character set.
For non-ASCII characters, you have to convert the string to the MacRoman encoding, see e.g. https://stackoverflow.com/a/13743834/1187415 for an example.
Note that
CGContextShowTextAtPointcannot display general Unicode strings, and even has problems with the Euro (€) character. ThedrawAtPoint:withFont:method ofNSStringdoes not have these limitations.