How to initialize UIColor from RGB values properly?

后端 未结 6 2320
春和景丽
春和景丽 2020-12-23 18:47

I am working on an iPhone application which uses various colors. When user selects the particular color button I set drawing color accordingly. I am getting the color for so

相关标签:
6条回答
  • 2020-12-23 19:30

    Here is a method that you can easily turn into a category on UIColor that will allow you to specify a color based on RGBA values of 0 - 255.

    + (UIColor *)colorFromRGBAWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha {
        return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha/255.0];
    }
    

    If you make it a UIColor category extension, you can use it like so:

    UIColor *myAwesomeColor = [UIColor colorFromRGBAWithRed:48 green:119 blue:167 alpha:255];
    
    0 讨论(0)
  • 2020-12-23 19:34

    You got several options

    Code

    CGFloat red = 16.0;
    CGFloat green = 97.0;
    CGFloat blue = 5.0;
    CGFloat alpha = 255.0;
    UIColor *color = [UIColor colorWithRed:(red/255.0) green:(green/255.0) blue:(blue/255.0) alpha:(alpha/255.0)];
    

    Color picker plugin for Interface Builder

    There's a nice color picker from Panic which works well with IB: http://panic.com/~wade/picker/

    Xcode plugin

    This one gives you a GUI for choosing colors: http://www.youtube.com/watch?v=eblRfDQM0Go

    Pods and libraries

    There's a nice pod named MPColorTools: https://github.com/marzapower/MPColorTools

    0 讨论(0)
  • 2020-12-23 19:37
    (ContentView.Layer.BorderColor) //CG Object
       = UIColor.LightGray.CGColor; 
    
    0 讨论(0)
  • 2020-12-23 19:39

    In Swift you can easily set your Background-Color for example of a cell like this:

    cell.backgroundColor = UIColor.init(red: 14.0/255.0, green: 114.0/255.0, blue: 199.0/255.0, alpha: 1)

    :-)

    0 讨论(0)
  • 2020-12-23 19:44

    Pragmatic approach with Swift.

    extension UIColor {
    
       convenience init(rgbColorCodeRed red: Int, green: Int, blue: Int, alpha: CGFloat) {
    
         let redPart: CGFloat = CGFloat(red) / 255
         let greenPart: CGFloat = CGFloat(green) / 255
         let bluePart: CGFloat = CGFloat(blue) / 255
    
         self.init(red: redPart, green: greenPart, blue: bluePart, alpha: alpha)
    
       }
    }
    
    0 讨论(0)
  • 2020-12-23 19:45

    The values are in the 0.0 to 1.0 range.

    E.g. divide by 255., but remember the decimal dot so you get floating point division and not integer division.

    Like

    selectedColor = [UIColor colorWithRed:14.0/255.0 green:114.0/255.0 blue:199.0/255.0 alpha:1];
    
    0 讨论(0)
提交回复
热议问题