Get Slightly Lighter and Darker Color from UIColor

前端 未结 19 2623
猫巷女王i
猫巷女王i 2020-12-07 07:08

I was looking to be able to turn any UIColor into a gradient. The way I am intending to do this is by using Core Graphics to draw a gradient. What I am trying to do is to ge

19条回答
  •  感情败类
    2020-12-07 07:39

    - (UIColor *)lighterColorForColor:(UIColor *)c
    {
        CGFloat r, g, b, a;
        if ([c getRed:&r green:&g blue:&b alpha:&a])
            return [UIColor colorWithRed:MIN(r + 0.2, 1.0)
                                   green:MIN(g + 0.2, 1.0)
                                    blue:MIN(b + 0.2, 1.0)
                                   alpha:a];
        return nil;
    }
    
    - (UIColor *)darkerColorForColor:(UIColor *)c
    {
        CGFloat r, g, b, a;
        if ([c getRed:&r green:&g blue:&b alpha:&a])
            return [UIColor colorWithRed:MAX(r - 0.2, 0.0)
                                   green:MAX(g - 0.2, 0.0)
                                    blue:MAX(b - 0.2, 0.0)
                                   alpha:a];
        return nil;
    }
    

    Use it like this:

    UIColor *baseColor = // however you obtain your color
    UIColor *lighterColor = [self lighterColorForColor:baseColor];
    UIColor *darkerColor = [self darkerColorForColor:baseColor];
    

    EDIT: as @Anchu Chimala pointed out, for maximum flexibility, these methods should be implemented as an UIColor category. Also, from @Riley's idea, it may be a better idea to make the color proprtionally darker or lighter instead of adding or subtracting constant values. As @jrturton pointed out, it's not necessary to manipulate the RGB components; it's better to modify the brightness property itself. All in all:

    @implementation UIColor (LightAndDark)
    
    - (UIColor *)lighterColor
    {
        CGFloat h, s, b, a;
        if ([self getHue:&h saturation:&s brightness:&b alpha:&a])
            return [UIColor colorWithHue:h
                              saturation:s
                              brightness:MIN(b * 1.3, 1.0)
                                   alpha:a];
        return nil;
    }
    
    - (UIColor *)darkerColor
    {
        CGFloat h, s, b, a;
        if ([self getHue:&h saturation:&s brightness:&b alpha:&a])
            return [UIColor colorWithHue:h
                              saturation:s
                              brightness:b * 0.75
                                   alpha:a];
        return nil;
    }
    @end
    

提交回复
热议问题