代码之家  ›  专栏  ›  技术社区  ›  Nurgling96

如何从“rgb(0,0,0)”这样的字符串创建UIColor?

  •  0
  • Nurgling96  · 技术社区  · 8 年前

    我有一个来自服务器的字符串,格式为“rgb(0,0,0)”,应该在某些UI元素上使用。

    主要问题是各种颜色,如“rgb(20120,4)”等。

    有没有一种方法来解析它 UIColor(red: 0, green: 0, blue: 0, alpha: 1) ?

    3 回复  |  直到 8 年前
        1
  •  7
  •   Martin R    3 年前

    有这么多可能的解决方案!这里有一个使用 NSScanner :

    extension UIColor {
        convenience init?(rgbString : String) {
            var red = 0.0
            var green = 0.0
            var blue = 0.0
            
            let scanner = NSScanner(string : rgbString)
            guard scanner.scanString("rgb(", intoString: nil)
                && scanner.scanDouble(&red)
                && scanner.scanString(",", intoString: nil)
                && scanner.scanDouble(&green)
                && scanner.scanString(",", intoString: nil)
                && scanner.scanDouble(&blue)
                && scanner.scanString(")", intoString: nil) else {
                    return nil
            }
            self.init(red: CGFloat(red/255.0), green: CGFloat(green/255.0), blue: CGFloat(blue/255.0), alpha: 1.0)
        }
    }
    

    使用示例:

    if let col = UIColor(rgbString: "rgb(20,120.5, 4)") {
        print(col)
    } else {
        print("invalid color specification")
    }
    

    Swift 3/4更新:

    extension UIColor {
        convenience init?(rgbString: String) {
            var red = 0.0
            var green = 0.0
            var blue = 0.0
            
            let scanner = Scanner(string: rgbString)
            guard scanner.scanString("rgb(", into: nil)
                && scanner.scanDouble(&red)
                && scanner.scanString(",", into: nil)
                && scanner.scanDouble(&green)
                && scanner.scanString(",", into: nil)
                && scanner.scanDouble(&blue)
                && scanner.scanString(")", into: nil) else {
                    return nil
            }
            self.init(red: CGFloat(red/255.0), green: CGFloat(green/255.0), blue: CGFloat(blue/255.0), alpha: 1.0)
        }
    }
    

    Swift 5更新:

    extension UIColor {
        convenience init?(rgbString: String) {
    
            let scanner = Scanner(string: rgbString)
            guard scanner.scanString("rgb(") != nil,
                  let red = scanner.scanDouble(),
                  scanner.scanString(",") != nil,
                  let green = scanner.scanDouble(),
                  scanner.scanString(",") != nil,
                  let blue = scanner.scanDouble(),
                  scanner.scanString(")") != nil else {
                    return nil
            }
            self.init(red: CGFloat(red/255.0), green: CGFloat(green/255.0), blue: CGFloat(blue/255.0), alpha: 1.0)
        }
    }
    
        2
  •  2
  •   OgreSwamp    8 年前

    下面是一个将字符串转换为 UIColor 。可能有更好的regex解决方案,但我在regex方面很差。

    func colorFromString(colorString: String) -> UIColor? {
        // strip down rgb and parenthesis
        let combinedCharacterSet = NSMutableCharacterSet.letterCharacterSet()
        combinedCharacterSet.addCharactersInString("()")
    
        let trimmedString = colorString.stringByTrimmingCharactersInSet(combinedCharacterSet)
        let rgbValueStrings = trimmedString.componentsSeparatedByString(",")
    
        if rgbValueStrings.count != 3 {
            return nil
        }
    
        if let r =  Double(rgbValueStrings[0]) where r >= 0 && r <= 255,
            let g =  Double(rgbValueStrings[1]) where g >= 0 && g <= 255,
            let b =  Double(rgbValueStrings[2]) where b >= 0 && b <= 255 {
            return UIColor(red: CGFloat(r/255), green: CGFloat(g/255), blue: CGFloat(b/255), alpha: 1.0)
        } else {
            return nil
        }
    }
    

    操场可以 downloaded here

        3
  •  1
  •   Twitter khuong291    8 年前

    你可以试试这个。

    import UIKit
    
    let string1 = "rgb(25.00,100.0,100)"
    
    let indexToRemoveTheLast = string1.endIndex.advancedBy(-1)
    let substring1 = string1.substringToIndex(indexToRemoveTheLast)
    let indexToRemoveTheFirst = string1.startIndex.advancedBy(4)
    let substring2 = substring1.substringFromIndex(indexToRemoveTheFirst)
    
    var colorsString = substring2.characters.split{$0 == ","}.map(String.init)
    let red = (Float(colorsString[0])!) / 255
    let green = (Float(colorsString[1])!) / 255
    let blue = (Float(colorsString[2])!) / 255
    
    let myColor = UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: 1)
    

    结果如下:

    enter image description here