我正在尝试向 UIImage
添加一个方便的初始化程序,这将允许我创建一个图像,其中给定的文本居中,并给定背景颜色:
我有以下代码:
public convenience init?(color: UIColor, withText: String, withTextColor: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let label = UILabel()
label.text = withText
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 40)
label.textColor = withTextColor
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
这会创建具有正确背景颜色的图像 - 但我不确定如何将 UILabel
嵌入图像中间。
编辑
最佳答案
属性字符串知道如何to draw themselves ,所以你不需要标签。他们还可以 tell you how big they are甚至包裹以适合可用的宽度。这是 Playground ,展示了如何从任何属性字符串获取图像:
import UIKit
import PlaygroundSupport
extension NSAttributedString {
func asImage(size: CGSize = .init(width: .max, height: .max)) -> UIImage {
UIGraphicsImageRenderer(bounds: boundingRect(with: size, options: [.usesLineFragmentOrigin], context: nil)).image { context in
self.draw(at: .zero)
}
}
}
let attributedString = NSAttributedString.init(string: "testing", attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
let image = attributedString.asImage()
let imageView = UIImageView(image: image)
PlaygroundPage.current.liveView = imageView
关于ios - 带有颜色和居中文本的 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58278226/