2013-06-30 120 views
4

請幫助我瞭解用下面的代碼的問題:CTFontGetGlyphsForCharacters始終返回false

NSString *fontName = @"ArialMT"; 
CGFloat fontSize = 20.0; 
CTFontRef fontRef = CTFontCreateWithName((CFStringRef)fontName, fontSize, NULL); 
NSString *characters = @"ABC"; 
NSUInteger count = characters.length; 
CGGlyph glyphs[count]; 
if (CTFontGetGlyphsForCharacters(fontRef, (const unichar*)[characters cStringUsingEncoding:NSUTF8StringEncoding], glyphs, count) == false) 
    NSLog(@"*** CTFontGetGlyphsForCharacters failed."); 

任何幫助表示讚賞。

回答

10

您正在獲取包含UTF-8編碼字符的C字符串,然後將其轉換爲unichar *。這是行不通的。 A unichar是一個16位UTF-16編碼字符。簡單的C語言轉換不會轉換字符編碼。

你要問其字符字符串的unichar數組:

NSString *fontName = @"ArialMT"; 
CGFloat fontSize = 20.0; 
CTFontRef fontRef = CTFontCreateWithName((CFStringRef)fontName, fontSize, NULL); 
NSString *string = @"ABC"; 
NSUInteger count = string.length; 
unichar characters[count]; 
[string getCharacters:characters range:NSMakeRange(0, count)]; 
CGGlyph glyphs[count]; 
if (CTFontGetGlyphsForCharacters(fontRef, characters, glyphs, count) == false) 
    NSLog(@"*** CTFontGetGlyphsForCharacters failed."); 
+0

一個很好的教訓。非常感激。 –