How to create an image from UILabel?

前端 未结 6 1816
情深已故
情深已故 2020-12-01 07:55

I\'m currently developing a simple photoshop like application on iphone. When I want to flatten my layers, the labels are at the good position but with a bad font size. Here

6条回答
  •  甜味超标
    2020-12-01 08:26

    extension UIImage {
    
        class func imageFrom(text: String, width: CGFloat, font: UIFont, textAlignment: NSTextAlignment, lineBreakMode: NSLineBreakMode) -> UIImage? {
            let label = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
            label.text = text
            label.font = font
            label.textAlignment = textAlignment
            label.lineBreakMode = lineBreakMode
    
            label.sizeToFit()
    
            UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0.0)
            label.layer.render(in: UIGraphicsGetCurrentContext()!)
            let img = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return img
        }
    
    }
    

    Using:

        let iv = UIImageView(image: UIImage.imageFrom(text: "Test For \nYarik", width: 537.0, font: UIFont.systemFont(ofSize: 30), textAlignment: .center, lineBreakMode: .byWordWrapping))
        iv.contentMode = .scaleAspectFit
    

提交回复
热议问题