gpt4 book ai didi

ios - 如何在 Swift 中从自定义文本生成 UIImage

转载 作者:搜寻专家 更新时间:2023-10-31 21:54:02 25 4
gpt4 key购买 nike

我正在尝试从 Swift3 中的自定义文本生成一个 UIImage

使用 iOS 控件,可以创建一个 UIImage,下面是代码:

class func imageWithText(txtField: UITextField) -> UIImage {
UIGraphicsBeginImageContextWithOptions(txtField.bounds.size, false, 0.0)
txtField.layer.render(in: UIGraphicsGetCurrentContext()!)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}

注意:我知道也可以在图像中添加一些文本,但我不想这样做。

有人可以帮我解决这个问题吗?谢谢!

最佳答案

这是一个 String 扩展,可以如下所示用于从 String 实例创建 UIImage 实例,没有需要像 UITextFieldUILabel 这样的 UI 控件:

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()

Playground Sampler

以下是实现上述预期效果的两种可能的实现方式:

UIGraphicsImageRenderer 方法(性能更高,Apple 推荐实现)

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
}

}

关于ios - 如何在 Swift 中从自定义文本生成 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51100121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com