Question

I was looking for sample which gives me mid colour from passed UIColor. In the following Example, Get Slightly Lighter and Darker Color from UIColor
can get lighter & darker colour from UIColor. But i need to get average/ mid colour from UIColor.

Anyone help me to solve this? Thanks in Advance.

Was it helpful?

Solution

The code to which you point steps the colour up or down by 0.2 in the first code example and adjusts brightness in the second.

By mid-colour I assume you mean one of two things: (1) the colour itself, or (2) something that isn't quite as light or quite as dark as the example code. To achieve the latter, all you need to do is change the brightness multiplier, e.g.

@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.15, 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.85
                               alpha:a];
    return nil;
}
@end

or is it that you are looking for a colour between two colours? Working on this now will edit again shortly.

Update: to get middle colour use:

- (UIColor *)betweenColor:(UIColor *)c andColor:(UIColor *)d
{
    CGFloat r, g, b, a;
    CGFloat r2, g2, b2, a2;
    [c getRed:&r green:&g blue:&b alpha:&a];
    [d getRed:&r2 green:&g2 blue:&b2 alpha:&a2];

    return [UIColor colorWithRed:(r + r2)/2
                           green:(g + g2)/2
                            blue:(b + b2)/2
                           alpha:a];
    return nil;
}

and call it like this:

UIColor *midColor = [self betweenColor:[UIColor whiteColor] andColor:[UIColor blackColor]];
self.view.backgroundColor = midColor;

and here's the HSB midpoint:

- (UIColor *)betweenColor:(UIColor *)c andColor:(UIColor *)d
{
    CGFloat h, s, b, a;
    CGFloat h2, s2, b2, a2;
    [c getHue:&h saturation:&s brightness:&b alpha:&a];
    [d getHue:&h2 saturation:&s2 brightness:&b2 alpha:&a2];
    return [UIColor colorWithHue:(h+h2)/2
                      saturation:(s+s2)/2
                      brightness:(b+b2)/2
                           alpha:a];    return nil;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top