【问题标题】:show a exactly Height of text in a TextField在 TextField 中显示准确的文本高度
【发布时间】:2017-01-01 15:53:59
【问题描述】:

我必须为验光师编写一个查看测试。所以他们需要数字准确地具有特定的高度。 他有一个 iPad 并将其流式传输到电视上。我知道我必须考虑电视的 PPI。这是我的代码:

func calcPoints() -> Float {
    // he gives the Visus with a TextField
    let visus = Float(textFieldVisus.text!)
    // Here you put in the PPI of the device
    let ppi = Float(textFieldDPI.text!)
    // Calculate the lenght of the Number
    let lenght = ((0.29 * 5) / visus!) * 5
    // Calculate the Points (because TextFiels work with Points)
    let points = ((ppi! / 25.4) * lenght) * 0.75
    // here you divide with 2 because you have a retina Display on the IPad
    return (points / 2)
}

func passeUIan() {
    // Now i can give the Points to the TextField
    textField1.bounds.size.width = CGFloat(calcPoints())
    textField1.bounds.size.height = CGFloat(calcPoints())
    textField1.font = UIFont(name: (textField1.font?.fontName)!, size: CGFloat(calcPoints()))
}

但是当我在电视上测量长度时,它是错误的。 通常它必须是 7.25 毫米,但大约是 9 毫米。 我不知道出了什么问题。我从 2 周开始搜索这个问题...

【问题讨论】:

  • 设置字体大小,不会显示正确高度的数字。您需要知道字体的内部尺寸(例如它的capHeight),以便选择具有正确高度的字体大小。

标签: ios ipad swift3 xcode8 ppi


【解决方案1】:

您需要先熟悉different font metrics。字体大小通常(但不总是)是升序和降序之间的差异。为了您的目的,大写字母的高度称为“大写高度”,小写字母的高度称为“x 高度”。

没有将字体大小转换为大写高度或 x 高度的公式。它们的关系因字体而异,甚至在字体中的变体(粗体、斜体、小型大写字母、显示、书本)也不同。

下面的函数使用二分搜索来寻找与您想要的高度(以英寸为单位)相匹配的磅值:

// desiredHeight is in inches
func pointSize(inFontName fontName: String, forDesiredCapHeight desiredHeight: CGFloat, ppi: CGFloat) -> CGFloat {
    var minPointSize: CGFloat = 0
    var maxPointSize: CGFloat = 5000
    var pointSize = (minPointSize + maxPointSize) / 2

    // Finding for exact match may not be possible. UIFont may round off
    // the sizes. If it's within 0.01 in (0.26 mm) of the desired height,
    // we consider that good enough
    let tolerance: CGFloat = 0.01

    while let font = UIFont(name: fontName, size: pointSize) {
        let actualHeight = font.capHeight / ppi * UIScreen.main.scale

        if abs(actualHeight - desiredHeight) < tolerance {
            return pointSize
        } else if actualHeight < desiredHeight {
            minPointSize = pointSize
        } else {
            maxPointSize = pointSize
        }

        pointSize = (minPointSize + maxPointSize) / 2
    }

    return 0
}

示例:在 Helvetica 中找出使大写字母 1 英寸高的磅值。 (326 是 iPhone 6 / 6S / 7 的 PPI,我曾经测试过):

let size = pointSize(inFontName: "Helvetica", forDesiredCapHeight: 1, ppi: 326)
label.font = UIFont(name: fontName, size: size)
label.text = "F"

(提示:UILabel 处理字体大小比 UITextField 好得多)

【讨论】:

  • 非常感谢,这对我帮助很大!
  • 我的问题是我从我的 Mac 在我的电视上流式传输。而且因为我的电视比我的 Mac 大,所以它会按比例放大,所以我测量了差异并给出了 Funktion 的因素。所以现在它可以工作了,谢谢大家的帮助!
猜你喜欢
  • 1970-01-01
  • 2020-09-26
  • 2018-06-21
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
  • 2020-11-22
  • 1970-01-01
  • 2013-08-24
相关资源
最近更新 更多