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

How to generate an UIImage from custom text in Swift

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

使用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!
    }

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

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

你可以使用这个函数,你可以向这个函数发送任何文本,我在里面创建 UILabel 并根据需要设置文本属性

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
}

这是一个 String 扩展,可以如下所示用于从 String 实例创建 UIImage 实例, 不需要 UI 控件如 UITextFieldUILabel 如原始问题中所要求的那样 :

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 方法(性能更高,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
    }
    
}