Home > Enterprise >  UIColorPickerViewController is changing the input color slightly
UIColorPickerViewController is changing the input color slightly

Time:09-02

I need to allow the user to choose a color on iOS. I use the following code to fire up the color picker:

    var picker = new UIColorPickerViewController();
    picker.SupportsAlpha = true;
    picker.Delegate = this;
    picker.SelectedColor = color.ToUIColor();   

    PresentViewController(picker, true, null); 

When the color picker displays, the color is always slightly off. For example:

input RGBA: (220, 235, 92, 255)

the initial color in the color picker might be:

selected color: (225, 234, 131, 255)

(these are real values from tests). Not a long way off... but enough to notice if you are looking for it.

I was wondering if the color picker grid was forcing the color to the nearest color entry - but if that were true, you would expect certain colors to stay fixed (i.e. if the input color exactly matches one of the grid colors, it should stay unchanged). That does not happen.

p.s. I store colors in a cross platform fashion using simple RGBA values. The ToUIColor converts to local UIColor using

new UIColor((nfloat)rgb.r, (nfloat)rgb.g, (nfloat)rgb.b, (nfloat)rgb.a);

CodePudding user response:

From the hints in comments by @DonMag, I've got some way towards an answer, and also a set of resources that can help if you are struggling with this.

The key challenge is that mac and iOS use displayP3 as the ColorSpace, but most people use default {UI,NS,CG}Color objects, which use the sRGB ColorSpace (actually... technically they are Extended sRGB so they can cover the wider gamut of DisplayP3). If you want to know the difference between these three - there's resources below.

When you use the UIColorPickerViewController, it allows the user to choose colors in DisplayP3 color space (I show an image of the picker below, and you can see the "Display P3 Hex Colour" at the bottom).

If you give it a color in sRGB, I think it gets converted to DisplayP3. When you read the color, you need to convert back to sRGB, which is the step I missed.

However I found that using CGColor.CreateByMatchingToColorSpace, to convert from DisplayP3 to sRGB never quite worked. In the code below I convert to and from DisplayP3 and should have got back my original color, but I never did. I tried removing Gamma by converting to a Linear space on the way but that didn't help.

    cg = new CGColor(...values...); // defaults to sRGB

    // sRGB to DisplayP3
    tmp = CGColor.CreateByMatchingToColorSpace(
        CGColorSpace.CreateWithName("kCGColorSpaceDisplayP3"),
        CGColorRenderingIntent.Default, cg, null);

    //  DisplayP3 to sRGB
    cg2 = CGColor.CreateByMatchingToColorSpace(
        CGColorSpace.CreateWithName("kCGColorSpaceExtendedSRGB"),
        CGColorRenderingIntent.Default, tmp, null);

Then I found an excellent resource: iOS Color Picker

  • Related