如何在Swift中从自定义文本生成UIImage [英] How to generate an UIImage from custom text in Swift

查看:169
本文介绍了如何在Swift中从自定义文本生成UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to generate an UIImage from custom text in Swift3.

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

Using iOS Controls, It's possible to create an UIImage, below is the code:

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

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

Note: I know it's also possible to add some text to an image, but I don't want to do like this.

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

Can someone help me to resolve this? Thank you!

推荐答案

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

You can use this function, you can send any text to this function, inside it i create UILabel and set text attribute as you like

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
}

这篇关于如何在Swift中从自定义文本生成UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆