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

use*_*786 3 text uiimage ios swift

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

使用iOS Controls,可以创建一个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!
    }
Run Code Online (Sandbox Code Playgroud)

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

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

Noo*_*ath 8

我使用以下String扩展名UIImage从字符串中创建实例,并且不需要UI控件(例如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()
Run Code Online (Sandbox Code Playgroud)

游乐场采样器

以下是用于实现上述效果的两种可能的实现方式。

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

}
Run Code Online (Sandbox Code Playgroud)

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
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 很好的解决方案。我还包括对 UIGraphicsEndImageContext() 的调用。或者,您可以考虑使用较新的 UIGraphicsImageRenderer - 它的性能更高,并且是 Apple 推荐的。 (2认同)

A.M*_*zer 5

您可以使用此功能,可以向该功能发送任何文本,在其中创建UILabel并根据需要设置text属性

func imageWith(name: String?) -> UIImage? {
     let frame = CGRect(x: 0, y: 0, width: 100, height: 100)
     let nameLabel = UILabel(frame: frame)
     nameLabel.textAlignment = .center
     nameLabel.backgroundColor = .lightGray
     nameLabel.textColor = .white
     nameLabel.font = UIFont.boldSystemFont(ofSize: 40)
     nameLabel.text = name
     UIGraphicsBeginImageContext(frame.size)
      if let currentContext = UIGraphicsGetCurrentContext() {
         nameLabel.layer.render(in: currentContext)
         let nameImage = UIGraphicsGetImageFromCurrentImageContext()
         return nameImage
      }
      return nil
}
Run Code Online (Sandbox Code Playgroud)