Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS CGColor versus UIColor

I am using 2 variations of the same color, a light and dark version, to create a gradient.

Code:

CAGradientLayer *gradient = [CAGradientLayer layer];

UIColor *light = [baseColor lightVersion];

UIColor *dark = [baseColor darkVersion];

gradient.colors = [NSArray arrayWithObjects:(id)[light CGColor], (id)[dark CGColor], nil];

The problem is, I noticed that the CGColor version of the original UIColor version is different. Why is that? What is the difference between the UIColor and CGColor and why are they different?

like image 340
Dan Vasile Avatar asked Nov 22 '13 08:11

Dan Vasile


People also ask

What is UIColor?

An object that stores color data and sometimes opacity.

What is CGColor in swift?

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).

How do I change the RGB color in Swift?

In Objective-C, we use this code to set RGB color codes for views: #define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0] view.


2 Answers

UIColor inherits from NSObject and is associated with UIKit Framework while CGColor is associated with CoreGraphics and CGColor is derived from CFType.

So if you are using UIKit elements then you can use UIColor, But if you are using drawing using Core Graphics or working with CALayer you must use CGColor.

As per Documentation of UIColor

Many methods in UIKit require you to specify color data using a UIColor object, and for general color needs it should be your main way of specifying colors. The color spaces used by this object are optimized for use on iOS-based devices and are therefore appropriate for most drawing needs. If you prefer to use Core Graphics colors and color spaces instead, however, you may do so.

like image 174
Nirav Gadhiya Avatar answered Oct 09 '22 05:10

Nirav Gadhiya


After reading your question, I tried a sample project in which I took a label with a background color having RGB values (100,100,100). And set its border color to same RGB values but it is CGColor but I found no difference in them. Refer attached image. Border width is 5 pixels.Label with same background color and border color

like image 42
Yogi Avatar answered Oct 09 '22 04:10

Yogi