在做IOS开发的时候,可能希望用颜色来代替图片,设置为view的背景,或者需要设置高亮状态下UIBUtton的背景,这个时候就需要将UIColor、或者rgb颜色通道转换为UIImage。 首先给UIImage建立一个Category,提供如下两个方法,分别是用UIColor创建UIImage,和rgba颜色通道来创建UIImage。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#import "UIImage+IAnime.h" @implementation UIImage (IAnime) +(UIImage *)initWithColor:(UIColor*)color rect:(CGRect)rect{ CGRect imgRect = CGRectMake(0, 0, rect.size.width, rect.size.height); UIGraphicsBeginImageContextWithOptions(imgRect.size, NO, 0); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, color.CGColor); CGContextFillRect(context, imgRect); UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return img; } +(UIImage *)initwithRgba:(CGFloat*)rgba rect:(CGRect)rect{ CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGColorRef colorRef = CGColorCreate(colorSpace,rgba); UIColor *color = [[UIColor alloc]initWithCGColor:colorRef]; CGColorRelease(colorRef); CGColorSpaceRelease(colorSpace); return [UIImage initWithColor:color rect:rect]; } @end |
然后就可以将UIColor颜色设置为UIButton的高亮(UIControlStateHighlighted)状态
1 2 3 4 5 6 7 8 9 |
-(void)colorToImage{ UIColor *color = [UIColor colorWithRed:0 green:146.0/255.0 blue:255.0/255.0 alpha:1]; UIImage *img = [UIImage initWithColor:color rect:uiButton.frame]; //或者 CGFloat *rgba = CGFloat{0,146.0/255.0,146.0/255.0,1}; UIImage *img = [UIImage initwithRgba:rgba rect:uiButton.frame]; [uiButton setBackgroundImage:img forState:UIControlStateHighlighted]; } |