从颜色创建的图像未添加到视图中?

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

我尝试从颜色 (tutorial) 创建图像,但它对我不起作用:此代码不显示任何图像:

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
    }

}

日志中的图像大小为 320,49,viewController 故事板和文件之间的连接很好。

谢谢

我觉得它不见了CGContextFillRect(context, rect);

尝试

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;