Iphone CGContextShowTextAtPoint for Japanese characters

后端 未结 4 2208
花落未央
花落未央 2020-12-06 13:03

I am working on an app where I am using CGContextShowTextAtPoint to display text to the screen. I want to also display Japanese characters, but CGContextS

4条回答
  •  鱼传尺愫
    2020-12-06 13:09

    I was able to get this working by using a reimplementation of CGFontGetGlyphsForUnichars by Jens Egeblad: GlyphDrawing.mm

    First load in a Japanese font as an otf file from the app bundle:

    // Load font file from otf file
    NSString *fontPath = [[NSBundle mainBundle] pathForResource:@"HStdNW8" ofType:@"otf"];
    CGDataProviderRef fontDataProvider = CGDataProviderCreateWithFilename([fontPath UTF8String]);
    CGFontRef _cgFont = CGFontCreateWithDataProvider(fontDataProvider);
    CGDataProviderRelease(fontDataProvider);
    

    Then you can convert your unichar text to glyphs and draw them:

    NSString *text = @"日本語"
    CGContextSetFont(context, _cgFont);
    CGContextSetFontSize(context, 12);
    CGGlyph textGlyphs[[text length]];
    
    unichar textChars[[text length]];
    for(int i = 0; i < [text length]; i++) {
        textChars[i] = [text characterAtIndex:i];
    }
    CMFontGetGlyphsForUnichars(_cgFont, textChars, textGlyphs, [text length]);
    CGContextShowGlyphsAtPoint(context, xCoord, yCoord, textGlyphs, [text length]);
    

提交回复
热议问题