将字形在sizeToFit

时间:2019-03-06 15:45:00

标签: ios uitextview nsattributedstring core-text textkit

我正在使用的应用程序支持数百种不同的字体。这些字体中的某些(尤其是脚本字体)具有明显的上升和下降形式。当使用其中的某些字体在sizeToFit()上调用UITextView时,我最终会得到明显的顶部和底部填充(左侧的图像)。目标是最终获得右侧的图像,以使最高字形与文本视图的边界框的顶部对齐。

UITextView Layout Examples

这是上图的日志:

Point Size: 59.0
Ascender:  70.21
Descender:  -33.158
Line Height:  103.368
Leading: 1.416
TextView Height: 105.0

我的第一个想法是查看文本第一行中每个字形的高度,然后计算容器顶部和最高字形顶部之间的偏移量。然后,我可以使用textContainerInset来相应地调整上边距。

我在UITextView子类中尝试过类似的操作:

for location in 0 ..< lastGlyphIndexInFirstLine {
    let glphyRect = self.layoutManager.boundingRect(forGlyphRange: NSRange(location: location, length: 1), in: self.textContainer)
    print(glphyRect.size.height) // prints 104.78399999999999 for each glyph
}

不幸的是,这不起作用,因为boundRect(forGlyphRange:in:)似乎没有返回字形本身的矩形(我猜这总是相同的值,因为它返回的是行片段的高度?)

这是解决此问题的最简单方法吗?如果是的话,如何计算文本视图顶部与文本第一行中最高字形顶部之间的距离?

1 个答案:

答案 0 :(得分:2)

使用TextKit似乎无法实现,但是可以直接使用CoreText来实现。具体来说,CGFont的getGlyphBBoxes字形空间单位返回正确的rect,然后可以将其转换为相对于字体大小的点。

信贷转到this answer是为了使我了解getGlyphBBoxes并记录如何将所得的rects转换为点。

下面是完整的解决方案。假设您有一个UITextView子类,并且预先设置了以下子类:

self.contentInset = .zero
self.textContainerInset = .zero
self.textContainer.lineFragmentPadding = 0.0

此函数现在将返回从文本视图边界的顶部到使用的最高字形的顶部的距离:

private var distanceToGlyphs: CGFloat {
    // sanity
    guard
        let font = self.font,
        let fontRef = CGFont(font.fontName as CFString),
        let attributedText = self.attributedText,
        let firstLine = attributedText.string.components(separatedBy: .newlines).first
    else { return 0.0 }

    // obtain the first line of text as an attributed string
    let attributedFirstLine = attributedText.attributedSubstring(from: NSRange(location: 0, length: firstLine.count)) as CFAttributedString

    // create the line for the first line of attributed text
    let line = CTLineCreateWithAttributedString(attributedFirstLine)

    // get the runs within this line (there will typically only be one run when using a single font)
    let glyphRuns = CTLineGetGlyphRuns(line) as NSArray
    guard let runs = glyphRuns as? [CTRun] else { return 0.0 }

    // this will store the maximum distance from the baseline
    var maxDistanceFromBaseline: CGFloat = 0.0

    // iterate each run
    for run in runs {
        // get the total number of glyphs in this run
        let glyphCount = CTRunGetGlyphCount(run)

        // initialize empty arrays of rects and glyphs
        var rects = Array<CGRect>(repeating: .zero, count: glyphCount)
        var glyphs = Array<CGGlyph>(repeating: 0, count: glyphCount)

        // obtain the glyphs
        self.layoutManager.getGlyphs(in: NSRange(location: 0, length: glyphCount), glyphs: &glyphs, properties: nil, characterIndexes: nil, bidiLevels: nil)

        // obtain the rects per-glyph in "glyph space units", each of which needs to be scaled using units per em and the font size
        fontRef.getGlyphBBoxes(glyphs: &glyphs, count: glyphCount, bboxes: &rects)

        // iterate each glyph rect
        for rect in rects {
            // obtain the units per em from the font ref so we can convert the rect
            let unitsPerEm = CGFloat(fontRef.unitsPerEm)

            // sanity to prevent divide by zero
            guard unitsPerEm != 0.0 else { continue }

            // calculate the actual distance up or down from the glyph's baseline
            let glyphY = (rect.origin.y / unitsPerEm) * font.pointSize

            // calculate the actual height of the glyph
            let glyphHeight = (rect.size.height / unitsPerEm) * font.pointSize

            // calculate the distance from the baseline to the top of the glyph
            let glyphDistanceFromBaseline = glyphHeight + glyphY

            // store the max distance amongst the glyphs
            maxDistanceFromBaseline = max(maxDistanceFromBaseline, glyphDistanceFromBaseline)
        }
    }

    // the final top margin, calculated by taking the largest ascender of all the glyphs in the font and subtracting the max calculated distance from the baseline
    return font.ascender - maxDistanceFromBaseline
}

您现在可以将文本视图的顶部contentInset设置为-distanceToGlyphs,以获得所需的结果。