iOS开发中的那些小技巧

前言:今天在写代码的过程中遇到一个需要修改系统navigationBar的背景色,我起初用的是barTintColor去修改但是防不住系统点击按钮的时候会有一个渲染高亮的效果,调了好久没有达到自己想要的效果,最后放弃用颜色来搞这个了,看了一下swift的API发现也可以用图片,有不好意思找UI(自己的demo找UI切图不太合适,只好来把颜色改成图片了)

正文开始啦:

先上一份OC的代码吧

+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

swift代码奉上

func imageWithColor(color:UIColor) -> (UIImage) {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return image!
}
刚刚接触swift不是特别久如果大神有更好的方法,还请不吝赐教,转载请附上原地址(不附上也没事^_^)
谢谢!

posted @ 2016-08-18 18:06  诸葛宅  阅读(256)  评论(0编辑  收藏  举报