我必须为配镜师编程看看测试。所以他们需要数字确切地具有特定的高度。 他有一个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()))
}
但是当我测量电视上的长度时,这是错误的。 Normaly它必须是7.25mm,但它大约是9mm。 我不知道出了什么问题。我从2个星期开始搜索这个问题...
答案 0 :(得分:0)
您需要先熟悉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
更好