您的位置:首页 > 移动开发 > IOS开发

ios给按钮图片根据不同的主题更改颜色

2016-12-21 11:02 274 查看
有时候在设计程序的时候,会涉及到主题模式的设计,根据不同的主体颜色,所对应的各个界面不同的按钮(导航栏、状态栏等),都需要对应的去改变颜色。

首先:用ps将按钮上图片的背景颜色改成白色的,如果图片本身有颜色,将无法通过代码的方式对其着色(很重要)。

核心代码:

+(UIImage *)colorizeImage:(UIImage *)baseImage withColor:(UIColor *)theColor {
UIGraphicsBeginImageContext(baseImage.size);

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(0, 0, baseImage.size.width, baseImage.size.height);

CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -area.size.height);

CGContextSaveGState(ctx);
CGContextClipToMask(ctx, area, baseImage.CGImage);

[theColor set];
CGContextFillRect(ctx, area);

CGContextRestoreGState(ctx);

CGContextSetBlendMode(ctx, kCGBlendModeMultiply);

CGContextDrawImage(ctx, area, baseImage.CGImage);

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return newImage;
}


只需要把对应的图片和所需要的颜色传进来,就可以得到想要颜色的图片了,但这里还有一个问题,你可能为按钮图片准备好了@3x的图片,但是还过于模糊,这时,需要修改一些这个方法:

UIGraphicsBeginImageContext(CGSizeMake(baseImage.size.width * baseImage.scale, baseImage.size.height * baseImage.scale));

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(0, 0, baseImage.size.width* baseImage.scale, baseImage.size.height* baseImage.scale);


在相同的地方进行替换,对图片的大小乘以baseImage.scale,就可以自动识别你传入图片是@2x还是@3x了,这样得到的图片就是清楚的图片了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: