Я использую следующее расширение String
для создания UIImage
экземпляров из строки и без необходимости управления пользовательским интерфейсом , например UITextField
или UILabel
, и использую его следующим образом:
var image: UIImage? =
"Test".image(withAttributes: [
.foregroundColor: UIColor.red,
.font: UIFont.systemFont(ofSize: 30.0),
], size: CGSize(width: 300.0, height: 80.0)
// Or
image = "Test".image(withAttributes: [.font: UIFont.systemFont(ofSize: 80.0)])
// Or
image = "Test".image(size: CGSize(width: 300.0, height: 80.0))
// Or even just
image = "Test".image()
Ниже приведены две возможные реализации для достижения желаемого эффекта, показанного выше.
Метод UIGraphicsImageRenderer (более производительный)
extension String {
/// Generates a `UIImage` instance from this string using a specified
/// attributes and size.
///
/// - Parameters:
/// - attributes: to draw this string with. Default is `nil`.
/// - size: of the image to return.
/// - Returns: a `UIImage` instance from this string using a specified
/// attributes and size, or `nil` if the operation fails.
func image(withAttributes attributes: [NSAttributedString.Key: Any]? = nil, size: CGSize? = nil) -> UIImage? {
let size = size ?? (self as NSString).size(withAttributes: attributes)
return UIGraphicsImageRenderer(size: size).image { _ in
(self as NSString).draw(in: CGRect(origin: .zero, size: size),
withAttributes: attributes)
}
}
}
Метод UIGraphicsImageContext (старая школа)
extension String {
/// Generates a `UIImage` instance from this string using a specified
/// attributes and size.
///
/// - Parameters:
/// - attributes: to draw this string with. Default is `nil`.
/// - size: of the image to return.
/// - Returns: a `UIImage` instance from this string using a specified
/// attributes and size, or `nil` if the operation fails.
func image(withAttributes attributes: [NSAttributedString.Key: Any]? = nil, size: CGSize? = nil) -> UIImage? {
let size = size ?? (self as NSString).size(withAttributes: attributes)
UIGraphicsBeginImageContext(size)
(self as NSString).draw(in: CGRect(origin: .zero, size: size),
withAttributes: attributes)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}