从颜色创建的图像未添加到视图中?
问题描述:
我尝试从颜色(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;
正确的,谢谢 – Paul 2015-03-13 20:07:49