Question

I have developed a color wheel using a circular gradient responding to a pan gesture recognizer and added a slider controlling the color's alpha value, as well as text fields that print out the R, G and B values.

I now need to implement a slider controlling the color's brightness, which i could not get to work using the following code :

- (void)changeBrightness:(id)sender {
    hellSlider = (UISlider *)sender;

    float red = r;
    float green = g;
    float blue = b;
    float alp = alphaSlider.value;
    UIColor *color2 = [UIColor colorWithRed:red green:green blue:blue alpha: alp];
    colorView.backgroundColor = color2;
}

In fact, i have no idea how to solve this yet. as there seems to be no brightness property that i can access, while i have no clue how to convert the color to a HSV value.

Any help is appreciated

Was it helpful?

Solution 3

Alright, I got it to work using the HSB color method as suggested.

Code :

- (void)changeBrightness:(id)sender {
    hellSlider = (UISlider *)sender;

    UIColor *currentColor = colorView.backgroundColor;
    CGFloat hue, saturation, brightness, alpha;
    BOOL success = [currentColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
    brightness = hellSlider.value;
    UIColor *newColor = [UIColor colorWithHue:hue saturation:saturationSlider.value brightness:hellSlider.value alpha:alphaSlider.value];

    colorView.backgroundColor = newColor;
    alphaText.text = [NSString stringWithFormat:@"%.2f",alphaSlider.value];
    brightnessText.text = [NSString stringWithFormat:@"%.2f",hellSlider.value];
    saturationText.text = [NSString stringWithFormat:@"%.2f",saturationSlider.value];

}

OTHER TIPS

You should deal with the HSB color method:

+ (UIColor *)colorWithHue:(CGFloat)hue saturation:(CGFloat)saturation brightness:(CGFloat)brightness alpha:(CGFloat)alpha

And see here for converting between color styles: Change from RGB to HSB on iPhone?

You need to convert the color into the HSB colour space, which gives you a parameter for 'brightness'.

Getting these values from a UIColor instance is straightforward, but involves passing values by reference, which may be alien to newer coders.

UIColor *currentColor = colorView.backgroundColor;
CGFloat hue, saturation, brightness, alpha;

BOOL success = [currentColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];

This puts the values into the respective parameters. You can then adjust the brightness component as necessary and then remake a UIColor object from the new values.

brightness = hellSlider.value * brightness; // example transformation, assuming hellSlider's value is bounded between 0 and 1

UIColor *newColor = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:alpha]; 
colorView.backgroundColor = newColor;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top