如何从UIColor获得反色? [英] How to get inverse color from UIColor?

查看:511
本文介绍了如何从UIColor获得反色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

e.g。黑色的反色应为白色。

e.g. The inverse color from black should be white.

推荐答案

----编辑----

---- EDIT ----

基于在@ amleszk的回答中,我用这种方法更新了UIColor类别:

Based on @amleszk's answer, I updated the UIColor category with this method:

- (UIColor *)inverseColor {
    CGFloat alpha;

    CGFloat white;
    if ([self getWhite:&white alpha:&alpha]) {
        return [UIColor colorWithWhite:1.0 - white alpha:alpha];
    }

    CGFloat hue, saturation, brightness;
    if ([self getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha]) {
        return [UIColor colorWithHue:1.0 - hue saturation:1.0 - saturation brightness:1.0 - brightness alpha:alpha];
    }

    CGFloat red, green, blue;
    if ([self getRed:&red green:&green blue:&blue alpha:&alpha]) {
        return [UIColor colorWithRed:1.0 - red green:1.0 - green blue:1.0 - blue alpha:alpha];
    }

    return nil;
}

----已弃用----

---- DEPRECATED ----

根据@ grc的答案,我使用这种方法创建一个UIColor类别:

Based on @grc's answer, I create a UIColor category with this method:

- (UIColor *)inverseColor {

    CGColorRef oldCGColor = self.CGColor;

    int numberOfComponents = CGColorGetNumberOfComponents(oldCGColor);

    // can not invert - the only component is the alpha
    // e.g. self == [UIColor groupTableViewBackgroundColor]
    if (numberOfComponents == 1) {
        return [UIColor colorWithCGColor:oldCGColor];
    }

    const CGFloat *oldComponentColors = CGColorGetComponents(oldCGColor);
    CGFloat newComponentColors[numberOfComponents];

    int i = numberOfComponents - 1;
    newComponentColors[i] = oldComponentColors[i]; // alpha
    while (--i >= 0) {
        newComponentColors[i] = 1 - oldComponentColors[i];
    }

    CGColorRef newCGColor = CGColorCreate(CGColorGetColorSpace(oldCGColor), newComponentColors);
    UIColor *newColor = [UIColor colorWithCGColor:newCGColor];
    CGColorRelease(newCGColor);

    return newColor;
}

这篇关于如何从UIColor获得反色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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