Tob
Tob

Reputation: 1025

Color in SCNNodes

I am trying to set the color of a SCNNode to a custom RGBA Color however when I try to the box will end up white:

let box = SCNBox(width: 4, height: 1, length: 4, chamferRadius: 0)
    let boxNode = SCNNode(geometry: box)
    myScene.rootNode.addChildNode(boxNode)

    boxNode.castsShadow = true


    box.firstMaterial?.diffuse.contents  = UIColor(red: 30, green: 150, blue: 30, alpha: 1)

This makes the box white however doing something like this works:

box.firstMaterial?.diffuse.contents  = UIColor.greenColor()

How can I make the box have a custom RGBA color?

-Thanks

Upvotes: 11

Views: 7395

Answers (2)

Benny Davidovitz
Benny Davidovitz

Reputation: 1202

For convenience, you can also add an UIColor extension

extension UIColor {

    convenience init(red: UInt, green: UInt, blue: UInt, alpha: UInt = 0xFF) {
        self.init(
            red: CGFloat(red) / 255.0,
            green: CGFloat(green) / 255.0,
            blue: CGFloat(blue) / 255.0,
            alpha: CGFloat(alpha) / 255.0
        )
    }
}

And then you can use it as follow:

box.firstMaterial?.diffuse.contents = UIColor(red: 30, green: 150, blue: 30, alpha: 1.0)

Alternatively if you wish to use hex values, add the next UIColor extension

extension UIColor {
    
    convenience init(argb: UInt) {
        self.init(
            red: CGFloat((argb & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((argb & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(argb & 0x0000FF) / 255.0,
            alpha: CGFloat((argb & 0xFF000000) >> 24) / 255.0
        )
    }
    
}

And use it as follow:

box.firstMaterial?.diffuse.contents = UIColor(argb: 0xFF1B98F5)

Happy Coding 👨‍💻

Upvotes: 0

dan
dan

Reputation: 9825

The values passed to the UIColor initializer need to be between 0 and 1. You should divide your rgb values by 255.

box.firstMaterial?.diffuse.contents  = UIColor(red: 30.0 / 255.0, green: 150.0 / 255.0, blue: 30.0 / 255.0, alpha: 1)

Upvotes: 16

Related Questions