Jonathan Jonathan - 3 months ago 32x
Objective-C Question

How to create an image from UILabel?

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's my code to flatten :


for (UILabel *label in arrayLabel) {
[label drawTextInRect:label.frame];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

Anybody can help me ?


From: pulling an UIImage from a UITextView or UILabel gives white image.

// iOS

- (UIImage *)grabImage {
    // Create a "canvas" (image context) to draw in.
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0);  // high res
    // Make the CALayer to draw in our "canvas".
    [[self layer] renderInContext: UIGraphicsGetCurrentContext()];

    // Fetch an UIImage of our "canvas".
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    // Stop the "canvas" from accepting any input.

    // Return the image.
    return image;

// Swift extension w/ usage. credit @Heberti Almeida in below comments

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

The usage:

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