Question

I'm using Xcode in order to make my first app. I want to add and RGB color picker for my text, so I could change the color of my text using the color picker. How can I do it?

Thanks for your time! :)

Was it helpful?

Solution

Take a look at GitHub. You'll find gazillion colour picker repos there. This was the first one I found when searching:

https://github.com/RSully/RSColorPicker

If you are new to programming you should perhaps stick with the built-in UI components. You could use two UIButtons to let the user select between "Red" and "Black" and set the text colour directly from the buttons actions.

I think a full blown colour picker is a big project for your first app.

A naïve implementation could simply create a number of colour wells looping through the possible colours.

UIView subclass with colour wells

The below ColorPickerView is a UIView subclass that illustrates this.

#import "ColorPickerView.h"

@implementation ColorPickerView

- (void)drawRect:(CGRect)rect {

    // Create a grid of n*n wells each with a seperate color --
    const int numberOfWells = 20;
    const int totalWells = numberOfWells * numberOfWells;

    // Figure out the size of each well --
    const CGSize size = self.bounds.size;
    const CGFloat boxHeight = floorf( size.height / numberOfWells);
    const CGFloat boxWidth = floorf( size.width / numberOfWells);

    CGContextRef context = UIGraphicsGetCurrentContext();

    // Loop through all the wells --
    for(int y = 0; y < numberOfWells; y++ ) {
        for(int x = 0; x < numberOfWells; x++ ) {

            int wellNumber = x + numberOfWells * y;

            // Assign each well a color --
            UIColor *boxColor = [self colorForWell:wellNumber ofTotal:totalWells];
            [boxColor setFill];

            CGRect box = CGRectMake(x*boxWidth, y*boxHeight, boxWidth, boxHeight);
            CGContextAddRect(context, box);
            CGContextFillRect(context, box);

        }
    }

}

-(UIColor*) colorForWell:(int) well ofTotal:(int) wells {

    CGFloat red = (CGFloat) well / wells;
    CGFloat green = well % (wells/3) / (CGFloat) (wells/3);
    CGFloat blue = well % (wells/9) / (CGFloat) (wells/9);

    return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}

@end

Let the user click on a colour and infer the colour from the location of the touch.

OTHER TIPS

It is impossible to teach you how to make a color picker. you should learn Objective C and maybe see some existing open-source project that do what you want to learn how to make your own (if you don't want to use and edit the existing one)... Take a look at these Color Pickers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top