How to get RGB values from UIColor?

后端 未结 15 1628
孤城傲影
孤城傲影 2020-11-28 22:27

I\'m creating a color object using the following code.

curView.backgroundColor = [[UIColor alloc] initWithHue:229 saturation:40 brightness:75 alpha:1];
         


        
15条回答
  •  孤城傲影
    2020-11-28 23:26

    Since iOS 2.0 there is a private instance method on UIColor called styleString which returns an RGB or RGBA string representation of the color, even for colors like whiteColor outside the RGB space.

    Objective-C:

    @interface UIColor (Private)
    
    - (NSString *)styleString;
    
    @end
    
    // ...
    
    [[UIColor whiteColor] styleString]; // rgb(255,255,255)
    [[UIColor redColor] styleString]; // rgb(255,0,0)
    [[UIColor lightTextColor] styleString]; // rgba(255,255,255,0.600000)
    

    In Swift you could use a bridging header to expose the interface. With pure Swift, you will need to create an @objc protocol with the private method, and unsafeBitCast UIColor with the protocol:

    @objc protocol  UIColorPrivate {
        func styleString() -> String
    }
    
    let white = UIColor.whiteColor()
    let red = UIColor.redColor()
    let lightTextColor = UIColor.lightTextColor()
    
    let whitePrivate = unsafeBitCast(white, UIColorPrivate.self)
    let redPrivate = unsafeBitCast(red, UIColorPrivate.self)
    let lightTextColorPrivate = unsafeBitCast(lightTextColor, UIColorPrivate.self)
    
    whitePrivate.styleString() // rgb(255,255,255)
    redPrivate.styleString() // rgb(255,0,0)
    lightTextColorPrivate.styleString() // rgba(255,255,255,0.600000)
    

提交回复
热议问题