如何使用swift将UIColor转换为字符串并将字符串转换为UIColor?

时间:2016-03-31 18:51:00

标签: ios swift uicolor

我有一个具有UIColor属性的对象:

class Beer: NSObject {
  var color: UIColor?
  ...
}

我将此保存到数据库中,因此我需要将此属性设置为有效的JSON类型,因此我想将其转换为字符串。如何转换为要存储的字符串,然后在使用该字符串加载时创建UIColor?

9 个答案:

答案 0 :(得分:10)

我已经为转换添加了一些示例,但仍然可以找到许多转换代码

对于从UIColor到十六进制字符串的转换,您可以使用以下代码:

extension UIColor {
    var rgbComponents:(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
        var r:CGFloat = 0
        var g:CGFloat = 0
        var b:CGFloat = 0
        var a:CGFloat = 0
        if getRed(&r, green: &g, blue: &b, alpha: &a) {
            return (r,g,b,a)
        }
        return (0,0,0,0)
    }
    // hue, saturation, brightness and alpha components from UIColor**
    var hsbComponents:(hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) {
        var hue:CGFloat = 0
        var saturation:CGFloat = 0
        var brightness:CGFloat = 0
        var alpha:CGFloat = 0
        if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha){
            return (hue,saturation,brightness,alpha)
        }
        return (0,0,0,0)
    }
    var htmlRGBColor:String {
        return String(format: "#%02x%02x%02x", Int(rgbComponents.red * 255), Int(rgbComponents.green * 255),Int(rgbComponents.blue * 255))
    }
    var htmlRGBaColor:String {
        return String(format: "#%02x%02x%02x%02x", Int(rgbComponents.red * 255), Int(rgbComponents.green * 255),Int(rgbComponents.blue * 255),Int(rgbComponents.alpha * 255) )
    }
}

样品使用:

let myColorBlack = UIColor.blackColor().webColor         //#000000ff
let myLghtGrayColor = UIColor.lightGrayColor().webColor  //#aaaaaaff
let myDarkGrayColor = UIColor.darkGrayColor().webColor 

有关详细信息,请查看:https://stackoverflow.com/a/28697136/4557505
https://gist.github.com/yannickl/16f0ed38f0698d9a8ae7

您可以将此字符串存储在数据库中,并在需要时将其检索

从HexString到UIColor

extension UIColor {
    public convenience init?(hexString: String) {
        let r, g, b, a: CGFloat

        if hexString.hasPrefix("#") {
            let start = hexString.startIndex.advancedBy(1)
            let hexColor = hexString.substringFromIndex(start)

            if hexColor.characters.count == 8 {
                let scanner = NSScanner(string: hexColor)
                var hexNumber: UInt64 = 0

                if scanner.scanHexLongLong(&hexNumber) {
                    r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
                    g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
                    b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
                    a = CGFloat(hexNumber & 0x000000ff) / 255

                    self.init(red: r, green: g, blue: b, alpha: a)
                    return
                }
            }
        }

        return nil
    }
}

用法:UIColor(hexString:“#ffe700ff”)

参考:https://www.hackingwithswift.com/example-code/uicolor/how-to-convert-a-hex-color-to-a-uicolor
https://github.com/yeahdongcn/UIColor-Hex-Swift
https://gist.github.com/arshad/de147c42d7b3063ef7bc

答案 1 :(得分:1)

您可以使用此功能

public static double[][] transpose(double arr[][]){
    int m = arr.length;
    int n = arr[0].length;
    double ret[][] = new double[n][m];

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            ret[j][i] = arr[i][j];
        }
    }

    return ret;
}

答案 2 :(得分:1)

这是针对以下内容的更新:

  1. Swift 5.0
  2. UIKit -n- SwiftUI 体系结构的
  3. 组合
  4. #RRGGBBAA / #RRGGBB颜色值

__

import UIKit
import SwiftUI

extension Color {

    init?(hexString: String) {

        let rgbaData = getrgbaData(hexString: hexString)

        if(rgbaData != nil){

            self.init(
                        .sRGB,
                        red:     Double(rgbaData!.r),
                        green:   Double(rgbaData!.g),
                        blue:    Double(rgbaData!.b),
                        opacity: Double(rgbaData!.a)
                    )
            return
        }
        return nil
    }
}

extension UIColor {

    public convenience init?(hexString: String) {

        let rgbaData = getrgbaData(hexString: hexString)

        if(rgbaData != nil){
            self.init(
                        red:   rgbaData!.r,
                        green: rgbaData!.g,
                        blue:  rgbaData!.b,
                        alpha: rgbaData!.a)
            return
        }
        return nil
    }
}

private func getrgbaData(hexString: String) -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)? {

    var rgbaData : (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)? = nil

    if hexString.hasPrefix("#") {

        let start = hexString.index(hexString.startIndex, offsetBy: 1)
        let hexColor = String(hexString[start...]) // Swift 4

        let scanner = Scanner(string: hexColor)
        var hexNumber: UInt64 = 0

        if scanner.scanHexInt64(&hexNumber) {

            rgbaData = { // start of a closure expression that returns a Vehicle
                switch hexColor.count {
                case 8:

                    return ( r: CGFloat((hexNumber & 0xff000000) >> 24) / 255,
                             g: CGFloat((hexNumber & 0x00ff0000) >> 16) / 255,
                             b: CGFloat((hexNumber & 0x0000ff00) >> 8)  / 255,
                             a: CGFloat( hexNumber & 0x000000ff)        / 255
                           )
                case 6:

                    return ( r: CGFloat((hexNumber & 0xff0000) >> 16) / 255,
                             g: CGFloat((hexNumber & 0x00ff00) >> 8)  / 255,
                             b: CGFloat((hexNumber & 0x0000ff))       / 255,
                             a: 1.0
                           )
                default:
                    return nil
                }
            }()

        }
    }

    return rgbaData
}

答案 3 :(得分:0)

Swift 3.0 IOS 10.x 不明白为什么这么复杂,这很有用......我一定错过了一些东西......仔细阅读,从第1项开始不是0。

 // convert color to string
 let color = userInfo["color"] as! UIColor       
 let diyColor = String(describing: color)

 // convert string back to color
 let diyValues = diyColor.components(separatedBy: " ")
 print("diyValues \(diyValues)")
        let returnedColor = UIColor(colorLiteralRed: diyValues[1].FloatValue()!, green: diyValues[2].FloatValue()!, blue: diyValues[3].FloatValue()!, alpha: diyValues[4].FloatValue()!)

也使用此扩展程序......

extension String {

func FloatValue() -> Float? {
    guard let doubleValue = Double(self) else {
        return nil
    }

    return Float(doubleValue)
}
}

答案 4 :(得分:0)

使用下面的UIColor扩展名将String转换为Color,反之亦然。

extension UIColor {


//Convert RGBA String to UIColor object
//"rgbaString" must be separated by space "0.5 0.6 0.7 1.0" 50% of Red 60% of Green 70% of Blue Alpha 100%
public convenience init?(rgbaString : String){
    self.init(ciColor: CIColor(string: rgbaString))
}

//Convert UIColor to RGBA String
func toRGBAString()-> String {

    var r: CGFloat = 0
    var g: CGFloat = 0
    var b: CGFloat = 0
    var a: CGFloat = 0
    self.getRed(&r, green: &g, blue: &b, alpha: &a)
    return "\(r) \(g) \(b) \(a)"

}
//return UIColor from Hexadecimal Color string
public convenience init?(hexaDecimalString: String) {

        let r, g, b, a: CGFloat

        if hexaDecimalString.hasPrefix("#") {
            let start = hexaDecimalString.index(hexaDecimalString.startIndex, offsetBy: 1)
            let hexColor = hexaDecimalString.substring(from: start)

            if hexColor.characters.count == 8 {
                let scanner = Scanner(string: hexColor)
                var hexNumber: UInt64 = 0

                if scanner.scanHexInt64(&hexNumber) {
                    r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
                    g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
                    b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
                    a = CGFloat(hexNumber & 0x000000ff) / 255
                    self.init(red: r, green: g, blue: b, alpha: a)
                    return
                }
            }
        }

        return nil
    }
// Convert UIColor to Hexadecimal String
func toHexString() -> String {
    var r: CGFloat = 0
    var g: CGFloat = 0
    var b: CGFloat = 0
    var a: CGFloat = 0
    self.getRed(&r, green: &g, blue: &b, alpha: &a)
    return String(
        format: "%02X%02X%02X",
        Int(r * 0xff),
        Int(g * 0xff),
        Int(b * 0xff)
    )
}

}

将此颜色字符串(stringWhite)保存到DataBase

let stringWhite =  UIColor.white.toHexString()

从DataBase读取颜色字符串时,使用下面的代码将stringWhite转换为UIColor

let whiteColor = UIColor(hexaDecimalString: stringWhite)

答案 5 :(得分:0)

我添加了自己的扩展程序,希望您欣赏:

extension UIColor {

    func toRGBAString(uppercased: Bool = true) -> String {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        self.getRed(&r, green: &g, blue: &b, alpha: &a)
        let rgba = [r, g, b, a].map { $0 * 255 }.reduce("", { $0 + String(format: "%02x", Int($1)) })
        return uppercased ? rgba.uppercased() : rgba
    }

}

答案 6 :(得分:0)

受@HardikDG代码启发,这些是简单的Objective C函数:

- (NSString *) colorToString:(UIColor *) color {
    CGFloat red, green, blue, alpha;
    [color getRed:&red green:&green blue:&blue alpha:&alpha];
    return [NSString stringWithFormat:@"%02x%02x%02x", (int)(red * 255), (int)(green * 255) , (int)(blue * 255)];
}

- (UIColor *) stringToColor:(NSString *) color {
    if([color length] != 6) {
        return nil;
    }

    NSScanner *scanner = [NSScanner scannerWithString:color];
    UInt64 hexNumber = 0;
    if ([scanner scanHexLongLong:&hexNumber]) {
        CGFloat r = ((hexNumber & 0xff000000) >> 24) / 255.0;
        CGFloat g = ((hexNumber & 0x00ff0000) >> 16) / 255.0;
        CGFloat b = ((hexNumber & 0x0000ff00) >> 8) / 255.0;
        CGFloat a = (hexNumber & 0x000000ff) / 255.0;

        return [UIColor colorWithRed:r green:g blue:b alpha:a];
    }

    return [UIColor whiteColor];
}

答案 7 :(得分:0)

使用NSCoding短一点:

到字符串:

colorString = String(数据:NSKeyedArchiver.archivedDataWithRootObject(color),编码:.utf8)

fromstring:

color = NSKeyedUnarchiver.unarchiveObjectWithData(colorString.dataUsingEncoding(.utf8))

答案 8 :(得分:-1)

将颜色转换为字符串对象。

let colorJSON: String = UIColor.white.hexValue()   //color to string

将字符串转换为颜色对象

view.backgroundColor = UIColor(hexString: colorJSON)   //string to respective color