Difference between cgColor and UIColor

5.9k Views Asked by At

in my project I'm having an array of colors. Should I use UIColor as the underlying type or cgColor?

Are there any best practices?

3

There are 3 best solutions below

0
On

CGColor

  • CGColor is the fundamental data type used internally by Core Graphics to represent colors. CGColor objects, and the functions that operate on them, provide a fast and convenient way of managing and setting colors directly, especially colors that are reused (such as black for text). CGColor is derived from CFTypeRef and inherits the properties that all Core Foundation types have in common.
  • Generally CGColor is used to apply color operations with Core Graphics contexts like CGImage, CGLayer etc...

UIColor

  • An object that stores color data and sometimes opacity (alpha value). When performing custom drawing, a UIColor object provides methods that set the fill or stroke colors of the current graphics context. A UIColor object is typically represented internally as a Core Graphics color (CGColor) in a Core Graphics color space (CGColorSpace). There are methods and properties that return the underlying color data.
  • UIColor, is used to apply color operations on UIKit interface elements like UIImage, UIView etc...

cgColor: An instance property of UIColor, relates UIColor and CGColor with each other.

Note: You can store reference to anyone but you must convert them into a relevant color class while dealing with color operations on graphical interface elements, to which it belongs.

0
On

Use UIColor and if you want to convert it anyTime

var cc = UIColor.red.cgColor

UIColor: Usual we use as background colour of views

cgColor: always used for layers (as fill or stroke) or borders of views

0
On

Since UIColor has the cgColor property I would say that the first is more convenient to use if you're doubtful.

UIColor is used widely in UIKit while cgColor is used only for CoreGraphics and CoreAnimation functions, so is more likely that an array that you'll need an array of UIColor