如何在 swift 中从高度确定文本的字体大小?.

  • 本文关键字:文本 字体 swift 高度 swift
  • 更新时间 :
  • 英文 :


我需要为图像添加文本水印。 文本的高度随图像的高度而变化。 现在我知道图像的高度,我知道文本的高度。 我怎么知道文本的字体大小? 总之,如何从高度确定文字的字体大小? 现在我的解决方案如下。有没有人有更好的方法? 谢谢!!!

/// - Parameter height: target height for font
func textFontSize(from height: CGFloat) -> CGFloat {
var fontSize: CGFloat = 30
var textFont = UIFont.systemFont(ofSize: fontSize)
while (textFont.lineHeight < (height * 4 / 5) ||
textFont.lineHeight > height){
//decrease font size
if textFont.lineHeight > height {
fontSize = fontSize - 0.5
// increase
}else if textFont.lineHeight < (height * 4 / 5) {
fontSize = fontSize + 0.5
}
textFont = UIFont.systemFont(ofSize: fontSize)
}
return fontSize
}

正确的方法已经过测试

/// - Parameter height: target height for font
func textFontSize(from height: CGFloat) -> CGFloat {
let defaultSize: CGFloat = 30
let defaultFont = UIFont.systemFont(ofSize: defaultSize)
let boundSize = self.size(withAttributes: [NSAttributedString.Key.font : defaultFont])
let pointsPerPixel = defaultFont.pointSize / boundSize.height
let desiredPointSize = height * pointsPerPixel
return desiredPointSize
}

最新更新