问题描述
因此,我希望这里的某人以前已经处理过这个问题并可以指导我。我想要做的是在图像上方绘制一些文本。我的问题是图像的大小可能如此之多,以至于文本太大或太小。我发现的所有内容都会说出要选择的字体大小,它会给我绘制矩形的大小。这对我来说不起作用,我想计算矩形的大小,然后找出正确的字体大小以适合该矩形。有人知道我该怎么做吗?
在此先感谢您的帮助。
解决方法
如果使用UILabel将文本添加到UIImage中,请考虑使用自动收缩功能。您需要根据示例图像的宽度定义最大字体大小。这是示例代码。
func addTextToImage(image: UIImage,text: String) -> UIImage? {
let imageView = UIImageView(image: image)
imageView.backgroundColor = UIColor.clear
imageView.frame = CGRect(x: 0,y: 0,width: image.size.width,height: image.size.height)
let label = UILabel(frame: CGRect(x: 0,height: 45.0))
label.backgroundColor = UIColor.clear
label.textAlignment = .center
label.textColor = UIColor.black
label.text = text
label.font = UIFont.systemFont(ofSize: 25)
label.numberOfLines = 1
label.adjustsFontSizeToFitWidth = true
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size,false,0)
imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
label.layer.render(in: UIGraphicsGetCurrentContext()!)
let imageWithText = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithText
}