Paul
Paul

Reputation: 6176

Image created from a color is not added to the view?

I try to create an image from a color ( tutorial ) but it does not work for me : this code does not show any image:

import UIKit

class ViewController: UIViewController {

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        let image = ViewController.imageFromColor(UIColor.redColor(), size: CGSizeMake(320,49), radius: 0)
        println("image \(image.size)")

        let imageView = UIImageView(image: image)
        imageView.center = self.view.center
        self.view.addSubview(imageView)
    }

    class func imageFromColor(color:UIColor, size:CGSize, radius:CGFloat)->UIImage
    {
        let rect = CGRectMake(0,0, size.width, size.height)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        CGContextSetFillColorWithColor(context, color.CGColor)
        var image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        UIGraphicsBeginImageContext(size)
        UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip()
        image.drawInRect(rect)
        image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }

}

The image size in the log is 320,49, the viewController is well connected between the storyboard and the file.

Thanks

Upvotes: 0

Views: 37

Answers (1)

ryancrunchi
ryancrunchi

Reputation: 475

I think it is missing CGContextFillRect(context, rect);

Try

let rect = CGRectMake(0, 0, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
let context = UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, rect);

var image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIGraphicsBeginImageContext(size)
UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip()
image.drawInRect(rect)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return image;

Upvotes: 1

Related Questions