6

请帮助我理解以下代码的问题:

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

任何帮助表示赞赏。

4

1 回答 1

14

您将获得一个包含 UTF-8 编码字符的 C 字符串,然后将其转换为unichar *. 那是行不通的。Aunichar是一个 16 位 UTF-16 编码的字符。一个简单的 C 转换不会转换字符编码。

您需要将字符串作为unichar. 在 Objective-C 中:

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

String在 Swift 中,您可以通过询问其utf16属性来获取 a 的 UTF-16 编码。这将返回 a UTF16View,然后您需要将其转换为Array

import Foundation
import CoreText

extension CTFont {
    func glyphs(for string: String) -> [CGGlyph]? {
        let utf16 = Array(string.utf16)
        var glyphs = [CGGlyph](repeating: 0, count: utf16.count)
        guard CTFontGetGlyphsForCharacters(font, utf16, &glyphs, utf16.count) else {
            return nil
        }
        return glyphs
    }
}

let font = CTFontCreateWithName("ArialMT" as CFString, 20, nil)
print(font.glyphs(for: "Hello"))
于 2013-06-30T18:31:10.963 回答