Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting UIColor to CGColor in swift

This is the Obj-C code:

CGContextSetStrokeColorWithColor(context, [[UIColor lightGrayColor] CGColor]);

How do I write it in swift.

like image 701
Shakti Chauhan Avatar asked Jan 07 '15 14:01

Shakti Chauhan


People also ask

What is the difference between UIColor and CGColor?

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

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


2 Answers

// Original answer.
var newColor = UIColor.lightGrayColor().CGColor

// Swift 3 version
var newColor = UIColor.lightGray.cgColor
like image 145
Onik IV Avatar answered Oct 12 '22 02:10

Onik IV


Oddly enough, as Swift has evolved to 3.0 the answer has evolved as well. I ran across this while converting some Objective C code to Swift. I hope this helps someone! :-) Here is what it is today:

context.setStrokeColor(UIColor.lightGray.cgColor)

And it's funny, this "light gray" answer is actually helping me debug some code too! Thank iou!

like image 5
George D Girton Avatar answered Oct 12 '22 03:10

George D Girton