您的位置:首页 > 产品设计 > UI/UE

IOS中UIImage与UIColor相互转化

2016-03-09 19:05 369 查看
相信在IOS开发中都用过UIImage与UIColor,你也有可能遇到过需要让他们相互转换的情况:比如为UIButton设置backgroundImage、为UIView设置backgroundColor。当然可以有其他的方式设置,但是有些情况下或许使用转化更简便:

一、UIColor转化为UIImage:

<span style="font-size:18px;">+ (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;
}</span>


在为按钮设置背景图片上时候就方便多了,不用引入真的图片:

<span style="font-size:18px;">UIButton *btn = [[UIButton alloc] init];
UIImage *bgImage = [UIImage imageWithColor:[UIColor grayColor]];
[btn setBackgroundImage:bgImage forState:UIControlStateNormal];</span>


二、UIImage转化为UIColor:

IOS中提供了直接将UIImage转化为UIColor的方法

<span style="font-size:18px;">UIColor *color=[UIColor colorWithPatternImage: [UIImage imageNamed:@"bg_login"]];</span>
如果需要给UIView设置背景图片就方便多了,不需要再在UIView增加一个UIImageView

<span style="font-size:18px;">UIView *headerView=[[UIView alloc]initWithFrame:cgrect];
/*
//背景
//cgrect=CGRectMake(0, 0, self.view.frame.size.width, 113);
UIImageView *bgImgView=[[UIImageView alloc]initWithFrame:cgrect];
[bgImgView setImage:img];
[headerView addSubview:bgImgView];
*/
headerView.backgroundColor=[UIColor colorWithPatternImage:img];</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: