如何以编程和动态的色调UIButton的背景图像? [英] How to tint the background images of an UIButton programmatically and dynamically?

查看:163
本文介绍了如何以编程和动态的色调UIButton的背景图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,或者一些可重用的框架,我很乐意在工作后共享。在这个应用程序中,用户应该能够从颜色主题列表中进行选择。因此,应用程序必须能够以一些相当动态的方式调色其UI元素。

I am working on an app - or rather on some re-usable "framework" which I am happy to share once it works. Within this app the user should be able to choose from a list of color themes. Therefore the app must be able to tint its UI elements in some rather dynamic way.

对于按钮,所有的着色都不起作用。必须在此处提供正确着色的背景图像。但是为每个人准备一套背景图片只是第二好。它不够动态和灵活。

For Buttons all the tinting does not work. Properly tinted background images must be supplied here. But preparing one set of background images for each them is just second best. It is not dynamic and flexible enough.

最后,一个解决方案可能是为选定和正常状态提供一个单色(灰色)渐变图像,并使用CoreGraphics或OpenGL以编程方式调色。但坦率地说,我不知道从那里开始。应该如何梯度看起来像,然后我如何以编程方式色调在任何给定的颜色?

In the end a solution may come down to providing one monochrome (grey) gradiented image for the selected and normal state and tint that image programmatically using CoreGraphics or OpenGL. But frankly, I do not know where to start there. How should the gradient look like and how would I then programmatically tint that in any given color?

几乎适用于UISegmentedControls,只是有点复杂。 :)任何覆盖UISegementedControl的通用解决方案也是高度赞赏。

Pretty much applies to UISegmentedControls, just a bit more complicated. :) Any generic solution that covers UISegementedControls too is highliy appreciated.

推荐答案

我做了一个UIImage类别下面的另一个帖子,我不能发现采取的图像和色调如下:

I made a UIImage category following another post that i cant find that takes the image and tints it as follows:

- (UIImage *)tintedImageWithColor:(UIColor *)tintColor {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
    CGContextRef context = UIGraphicsGetCurrentContext();


    CGContextTranslateCTM(context, 0, self.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);

    // draw alpha-mask
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGContextDrawImage(context, rect, self.CGImage);

    // draw tint color, preserving alpha values of original image
    CGContextSetBlendMode(context, kCGBlendModeSourceIn);
    [tintColor setFill];
    CGContextFillRect(context, rect);

    UIImage *coloredImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return coloredImage;
}

这将拍摄图像并用alpha值填充所有区域与给定的颜色。

This will take the image and fill in all of the areas with an alpha value with the given color.

这篇关于如何以编程和动态的色调UIButton的背景图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆