CGContextShowTextAtPoint
画面にテキストを表示するために使用しているアプリに取り組んでいます。日本語の文字も表示したいのですがCGContextShowTextAtPoint
、入力としてC文字列を取ります。A)日本語の文字をC文字列に変更するにはどうすればよいですか?これが不可能な場合、B)日本語の文字を手動で画面に印刷するにはどうすればよいですか(drawRectメソッド内)。
前もって感謝します。
CoreText は次のことに役立ちます。
CTFontGetGlyphsForCharacters
(iOS 3.2 以降) Unicode 文字をグリフにマップしますCTFontDrawGlyphs
(iOS 4.2 以降) グリフを CGContext に描画します。注意。CGContextShowGlyphs
動作するはずですが、UniChars をグリフに変換する方法が見つかりませんでした。詳細はこちら:
古い、iOS 3.2以前の回答
これには UIKit を使用する必要があります。
開始するにはチェックアウト[NSString drawAtPoint:...]
してください。
このSOの質問も役に立ちます。
彼らが CoreGraphic のテキストで何を考えていたのかはわかりませんが、役に立ちません。
Jens Egeblad: GlyphDrawing.mmによる CGFontGetGlyphsForUnichars の再実装を使用して、これを機能させることができました。
まず、アプリ バンドルから日本語フォントを otf ファイルとして読み込みます。
// 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);
次に、unichar テキストをグリフに変換して描画できます。
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]);
これは %topic starter% に役立つかもしれません。Rhythmic Fistman の素晴らしいアドバイスに感謝します!
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSelectFont (context, [self.font.fontName cStringUsingEncoding:NSASCIIStringEncoding], self.font.pointSize, kCGEncodingMacRoman);
CGContextSetCharacterSpacing(context, characterSpacing);
CGContextSetFillColorWithColor(context, [self.textColor CGColor]);
CGAffineTransform myTextTransform = CGAffineTransformScale(CGAffineTransformIdentity, 1.f, -1.f );
CGContextSetTextMatrix (context, myTextTransform);
CGGlyph glyphs[self.text.length];
CTFontRef fontRef = CTFontCreateWithName((CFStringRef)self.font.fontName, self.font.pointSize, NULL);
CTFontGetGlyphsForCharacters(fontRef, (const unichar*)[self.text cStringUsingEncoding:NSUnicodeStringEncoding], glyphs, self.text.length);
float centeredY = (self.font.pointSize + (self.frame.size.height- self.font.pointSize)/2)-2;
CGContextShowGlyphsAtPoint(context, rect.origin.x, centeredY, (const CGGlyph *)glyphs, self.text.length);
CFRelease(fontRef);