Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a NSString to a cString for use with CGContextShowTextAtPoint

I am drawing a String using CGContextShowTextAtPoint. Thus I need to convert my NSString I want to draw into c Strings. Unfortunately special symbols like the euro currency symbol are not correctly shown.

CGContextSelectFont(currentContext, "TrebuchetMS", 15, kCGEncodingMacRoman);

CGContextShowTextAtPoint(currentContext, 0, 0, [myString cStringUsingEncoding:[NSString defaultCStringEncoding]], [myString length]);

I tried it with the kCGEncodingFontSpecific encoding in the CGContextSelectFont function but that didn't work either.

For performance reasons I need to use the CG Function, not the drawInRect functions provieded by NSString.

Maybe you can help me!

PS: I know this is an often issued topic, but I cannot figure out why I can't get it working ...

like image 634
Erik Avatar asked Oct 14 '09 06:10

Erik


1 Answers

The "special symbols" you are referring to are supported by the Unicode encoding of NSString, but not the MacRoman encoding used by your Core Graphics font drawing routines (the only two encodings you can set using CGContextSelectFont() are kCGEncodingMacRoman and kCGEncodingFontSpecific). That's the disadvantage of the CGContextShowTextAtPoint() route for drawing text. Because of this, I use NSString's -drawAtPoint: method whenever I need to manually draw text within a Core Graphics context.

As far as performance goes, in a comment on an earlier answer, Kyle had benchmarked drawAtPoint: as drawing 75 times per second versus CGContextShowTextAtPoint() drawing 99 times per second. That's not a tremendous difference in draw speed, so you're not gaining a lot by going this way. In my experience, -drawAtPoint: has been more than fast enough for my applications.

EDIT (10/14/2009): As pointed out by Sixten Otto, I misread my own code. UTF-8 does support the full character range, the font's MacRoman does not.

like image 169
Brad Larson Avatar answered Oct 04 '22 21:10

Brad Larson