How to create an image from UILabel?

前端 未结 6 1815
情深已故
情深已故 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:29

    I have created a Swift extension to render the UILabel into a UIImage:

    extension UIImage {
        class func imageWithLabel(label: UILabel) -> UIImage {
            UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0.0)
            label.layer.renderInContext(UIGraphicsGetCurrentContext()!)
            let img = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return img
        }
    }
    

    EDIT: Improved Swift 4 version

    extension UIImage {
        class func imageWithLabel(_ label: UILabel) -> UIImage {
            UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0)
            defer { UIGraphicsEndImageContext() }
            label.layer.render(in: UIGraphicsGetCurrentContext()!)
            return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
        }
    }
    

    The usage is simple:

    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: 22))
    label.text = bulletString
    let image = UIImage.imageWithLabel(label)
    

提交回复
热议问题