0

I am using UITextField.
I enter characters using the keyboard in UITextField.
When I tap the return button on the keyboard, I will display sentences in UILabel.
I would like to convert from UILabel to image after I display the characters in UILabel.
However, I do not know how to convert from UILabel to image.
Is there a better way?

@IBOutlet var messageLabel: UILabel!
@IBOutlet var messageField: UITextField!

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    messageLabel.text = messageField.text

    //Here I would like to convert from UILabel to image.
    //UILabel → image

}
ginger
  • 69
  • 9
  • first, what you mean with: " I display the characters on UITextField in UILabel." ? – mugx Dec 12 '17 at 02:40
  • sorry. I will correct a few sentences of the explanation. – ginger Dec 12 '17 at 02:51
  • What does the code in your question have to do with converting a label to an image? – rmaddy Dec 12 '17 at 03:12
  • @rmaddy Thank you.I would like to convert from UILabel to image. – ginger Dec 12 '17 at 03:21
  • @ginger I know what you are asking. I'm asking you what the current code in your question has to do with your actual question? Your actual question (converting a UILabel to a UIImage) is not in any way related to a text field. – rmaddy Dec 12 '17 at 03:22

2 Answers2

1

You can use UIGraphicsBeginImageContextWithOptions to begin an Image context and then you can use UIView method func drawHierarchy(in rect: CGRect, afterScreenUpdates afterUpdates: Bool) -> Bool to draw the label contents on it:


let label = UILabel(frame: CGRect(origin: .zero, size: CGSize(width: 200, height: 50)))
label.text = "StackOverflow"
label.backgroundColor = UIColor.red.withAlphaComponent(0.2)
label.textColor = .blue
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 24)

UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0)
label.drawHierarchy(in: label.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

enter image description here

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
-3

You can create a new IBOutlet of type UIImage, messageImage, and add the image you want into there. When you want to convert the label use the isHidden function to hide messageLabel and show messageImage.

messageLabel.isHidden = true
messageImage.isHidden = false
sn8wman
  • 149
  • 1
  • 7
  • Thank you for your advice.However, I do not want to hide the sentences of UILabel. – ginger Dec 12 '17 at 03:16
  • How is that different than converting UILabel to UIImage? Either way the UILabel no longer shows/exists. – sn8wman Dec 12 '17 at 03:22
  • @sn8wman The two are not even remotely similar. The question is asking how to create an image from the contents of a dynamic label. – rmaddy Dec 12 '17 at 03:32