How to use CGColorCreate to get white with Swift in iOS

3.3k Views Asked by At

Maybe I'm misinterpreting the information out there but in my code I have:

let color = CGColorCreate(CGColorSpaceCreateDeviceRGB(), [1.0, 1.0, 1.0, 1.0])

Which compiles fine but the text is always black no matter what I set the values to. What should the line look like to get white text?

3

There are 3 best solutions below

0
On

Did you check your lighting? Try to add the following:

scnView.autoenablesDefaultLighting = true
0
On

I think you are missing out the opacity of the colour space. I was able to get a bright, light orange with opacity with this [1.0, 0.5, 0.5, 0.2]. The opacity of the colour is 0.2 in my example.

let colour = CGColorCreate(CGColorSpaceCreateDeviceRGB(), [1.0, 0.5, 0.5, 0.2])

Set the opacity to 1 for a solid colour.

colour? I'm British old boy!

EDIT: Opps, I think I answered to the wrong question.

0
On

I was having the same problem when trying to draw text onto an image. I now found out that at least on iOS 8

    CGContextSetFillColorWithColor(context, CGColorCreate(CGColorSpaceCreateDeviceRGB(), [1.0, 1.0, 1.0, 1.0]))

doesn't really do anything. To set the color of the text, I rather had to add an attribute to the Dictionary that is in the withFont parameter of

    text.drawInRect(rectText, withFont: font)

Example:

Assuming we already have an UIImage image

    let font = UIFont(name: "Helvetica", size: 18)
    let text: NSString = "String to draw"
    let rect = CGRectMake(0, 0, image.size.width, image.size.height)
    UIGraphicsBeginImageContextWithOptions(CGSize(width: rect.width, height: rect.height), true, 0)
    image.drawInRect(rect)
    let attr: NSDictionary = [NSFontAttributeName : font!, NSForegroundColorAttributeName : UIColor.whiteColor() ]
    let size = text.sizeWithAttributes(attr)
    let rectText = CGRectMake(image.size.width-size.width, image.size.height-(size.height+4), image.size.width-(size.width+4), image.size.height)
    text.drawInRect(rectText, withAttributes: attr)
    let newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

This example borrows heavily from the blog post at http://www.bytearray.org/?p=5416.