代码之家  ›  专栏  ›  技术社区  ›  agibson007

获取具有下伸的ui字体的所有字形

  •  1
  • agibson007  · 技术社区  · 7 年前

    有没有一种方法可以获取包含真正下行的uifont的所有字形?似乎使用ctlinegettypographicbounds不准确,并且为每一行返回完全相同的下降值。我以为它会提供我需要的信息,但它没有。所以现在我想看看我是否可以用包含真正后代的字形构建一个字符集,除非另有方法。最终的目标是能够看到一行文本是否低于基线。

      let line = CTLineCreateWithAttributedString(NSAttributedString(string: s, attributes: attr))
      //let's get the real descent test
       var a : CGFloat = 0
       var d : CGFloat = 0
       var l : CGFloat = 0
       let bounds = CTLineGetTypographicBounds(line, &a, &d, &l)
       print("the descent is \(d)")
       print("the ascent is \(a)")
       print("the leading is \(l)")
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   rmaddy    7 年前

    由于您的实际目标似乎是确定字符串是否包含带下伸的字符,因此可以使用核心文本查看每个字形的边界矩形。如果边界矩形的原点为负,则表示glyph从基线以下开始。这适用于以下字符: y 而且 , .

    func checkDescender(string: String) {
        let uiFont = UIFont.systemFont(ofSize: 14) // Pick your font
        let font = CTFontCreateWithName(uiFont.fontName as CFString, uiFont.pointSize, nil)
        for ch in string.unicodeScalars {
            let utf16codepoints = Array(ch.utf16)
            var glyphs: [CGGlyph] = [0, 0]
            let hasGlyph = CTFontGetGlyphsForCharacters(font, utf16codepoints, &glyphs, utf16codepoints.count)
            if hasGlyph {
                let rect = CTFontGetBoundingRectsForGlyphs(font, .default, glyphs, nil, 1)
                // print("\(ch) has bounding box of \(rect)")
                if rect.origin.y < 0 {
                    print("\(ch) goes below the baseline by \(-rect.origin.y)")
                }
            }
        }
    }
    
    checkDescender(string: "Ymy,")
    

    您可能需要添加额外的检查,以仅查看字母,具体取决于您的需要。

    推荐文章