CTFontGetGlyphsForCharacters always returns false

给你一囗甜甜゛ 提交于 2019-12-06 03:04:59

问题


Please help me understand the problem with the following code:

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.");

Any help is appreciated.


回答1:


You are getting a C string containing UTF-8 encoded characters and then casting it to unichar *. That won't work. A unichar is a 16-bit UTF-16-encoded character. A simple C cast won't convert the character encoding.

You need to ask the string for its characters as an array of 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.");


来源:https://stackoverflow.com/questions/17393076/ctfontgetglyphsforcharacters-always-returns-false

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!