Proper way to convert CGColors between colorspaces Proper way to convert CGColors between colorspaces ios ios

Proper way to convert CGColors between colorspaces

Apple added this API in iOS 9 and macOS 10.11:

  • ObjC: CGColorCreateCopyByMatchingToColorSpace
  • Swift: CGColor.converted(to:intent:options:)

Apple's official response to rdar #12141580 where I requested exposing CGColorTransform:

Thanks very much for your feedback.

Engineering has determined that the behavior will not be changed based on the following information:

Use ColorSync.

If you have questions regarding the resolution of this issue, please update your bug report with that information.

We are now closing this bug report.

Please be sure to regularly check new Apple releases for any updates that might affect this issue.

Whoever wrote that response obviously felt compelled to explain the decision in great detail. Especially a decision that recommends the use of a highly complex API such as ColorSync.

The question explicitly says they want to avoid drawing on a bitmap context created solely for the purpose of converting colors, but i didn't realize and came up with this.

I'll leave this as reference for anyone which could stumble on this question and want to know how you would do the transformation by drawing on a temporary bitmap

CGColorRef source;CGColorSpaceRef targetColorSpace;int components = CGColorSpaceGetNumberOfComponents(targetColorSpace);CGFloat temp-buffer[components];CGContextRef temp-bmp = CGBitmapContextCreate(    temp-buffer,    1,1,8 * sizeof(CGFloat),components,    targetColorSpace,    kCGBitmapFloatComponents );CGContextSetFillColorWithColor(temp-bmp,source);CGContextFillRect(temp-bmp,CGRectMake(0,0,1,1));CGColor target = CGColorCreate(targetColorSpace,temp-buffer);/* then you cleanup and destroy created objects */

I didn't try this code, it could need some fixes.