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

时间:2016-04-04 16:04:33

标签: ios swift parsing uicolor

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

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

有没有办法在像UIColor(red: 0, green: 0, blue: 0, alpha: 1)之类的东西中解析它?

3 个答案:

答案 0 :(得分:5)

There are so many possible solutions! Here is one using 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)
    }
}

Usage example:

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

Update for 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)
    }
}

答案 1 :(得分:2)

Here is a method which will convert your string to the UIColor. Possibly there is even better solution with regex, but I'm pretty bad in 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
    }
}

and playground can be downloaded here

答案 2 :(得分:1)

你可以试试这个。

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