Search code examples
iosobjective-cxcodergbhsv

Slider altering the brightness of UIColor


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


Solution

  • 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];
    
    }