2

我试图强制 NSLayoutManager 在某个范围内绘制具有不同属性的字形,但它仍然使用在 NSTextStorage 对象中设置的属性。

我试图从不同的字体创建 NSGlyph 并将其替换为 NSTypesetter 字形存储中的字体。但它是无用的 - 布局管理器仍然使用文本存储属性字符串中指定的字体和颜色绘制该字形。

public override func drawGlyphs(forGlyphRange glyphsToShow: NSRange, at origin: NSPoint) {
    // now set glyphs for invisible characters
    if PreferencesManager.shared.shouldShowInvisibles == true {
        var spaceRanges = [NSRange]()
        let charRange = self.characterRange(forGlyphRange: glyphsToShow, actualGlyphRange: nil)
        var substring = (self.currentTextStorage.string as NSString).substring(with: charRange)

        let spacesExpression = try? NSRegularExpression(pattern: "[ ]", options: NSRegularExpression.Options.useUnicodeWordBoundaries)
        let substringRange = NSRange(location: 0, length: substring.characters.count)
        if let matches = spacesExpression?.matches(in: substring, options: .withoutAnchoringBounds, range: substringRange) {
            for match in matches {
                spaceRanges.append(NSRange(location: charRange.location + match.range.location, length: 1))
            }
        }

        for spaceRange in spaceRanges {
            let invisibleFont = Font(name: "Gill Sans", size: 11) ?? Font.systemFont(ofSize: 11)

            // get any glyph to test the approach
            var glyph = invisibleFont.glyph(withName: "paragraph")

            // replce the glyphs
            self.typesetter.substituteGlyphs(in: spaceRange, withGlyphs: &glyph)

        }
    }
    // BUT LAYOUT MANAGER IGNORES THE FONT OF THE GLYPH I CREATED
    super.drawGlyphs(forGlyphRange: glyphsToShow, at: origin)
}

如何强制布局管理器在某个范围内忽略这些属性并使用我需要的字体和颜色绘制我创建的字形?我需要这个,因为我正在研究绘制隐形字符的最有效方法。

4

1 回答 1

1

您在这里直接修改排字机,但是当您调用 时super,它将重新完成所有工作。相反,您可能会覆盖getGlyphs(in:glyphs:properties:characterIndexes:bidiLevels:),调用super然后交换您想要的任何字形。或者,您可以在致电setGlyphs(...)之前致电此处super

请参阅在 NSTextView中显示隐藏字符,以了解您尝试使用已弃用的方法执行的操作的示例。我相当肯定replaceGlyphAtIndex会被setGlyphs.

于 2016-10-06T14:39:33.970 回答