mostlyharmless
mostlyharmless

Reputation: 11

cString fails when given Russian characters on iPhone

I think this is pretty basic. I have the following code which writes text to a file for me:

    float curpo = CGContextGetTextPosition(ref).x;
    float newpo = 0;
    float textw = 0;

    const char *text = [userName cStringUsingEncoding:NSUTF8StringEncoding];
    CGContextSetTextDrawingMode(ref, kCGTextInvisible);
    CGContextShowTextAtPoint (ref, 0, pos, text, strlen(text));
    newpo = CGContextGetTextPosition(ref).x;
    textw = newpo - curpo;

It works fine with traditional english text, but when I pass in Russian or other cyrillic characters, the text comes out all jumbled. How can I fix this?

Upvotes: 1

Views: 186

Answers (1)

iccir
iccir

Reputation: 5128

For each byte in text, CGContextShowTextAtPoint() is going to map it to a glyph in the CGContextRef's current font. This is at a lower level than you probably want.

To draw a string which may contain any glyphs from any language, use the string drawing methods in UIStringDrawing.h . Something like this:

UIGraphicsPushContext(context);
[userName drawAtPoint:pos withFont:[UIFont systemFontOfSize:16]];
UIGraphicsPopContext();

If you need finer-grain control, you can look at the CoreText frame and create a CFAttributedString from your NSString, then create a CTFramesetterRef via CTFramesetterCreateWithAttributedString(), create a CTFrameRef from that, and draw it to the context using CTFrameDraw().

Upvotes: 2

Related Questions