2016-03-31 13 views
5

Ho un oggetto con una proprietà UIColor:Come convertire UIColor in stringa e stringa in UIColor usando swift?

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

sto risparmiando ad un DB, quindi ho bisogno di rendere questa proprietà in un tipo JSON valido, per cui sto pensando di convertirlo in un stringa. Come posso convertire in una stringa da archiviare, e quindi quando carico usando quella stringa per creare UIColor?

+0

è possibile convertire l'UIColor in codice colore esadecimale poi conservarlo nel DB e l'uso possibile utilizzare tale codice direttamente al recupero o convertirlo in UIColor – HardikDG

+0

migliore per conservare i componenti RGB e alfa come valori float. Controlla questo uno -> http: // stackoverflow.it/questions/23835093/storing-uicolor-object-in-core-data –

+0

ti dispiacerebbe scrivere una risposta completa? – Jaime

risposta

10

ho messo un po 'del campione sia per la conversione, ancora si possono trovare molti codice per la conversione

Per la conversione da UIColor a stringa esadecimale è possibile utilizzare il seguente codice: utilizzo

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

Campione :

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

Per maggiori informazioni è possibile controllare: https://stackoverflow.com/a/28697136/4557505
https://gist.github.com/yannickl/16f0ed38f0698d9a8ae7

È possibile memorizzare questa stringa all'interno del db e recuperarla quando ne avete bisogno

Da HexString a 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 
    } 
} 

Usage: UIColor (hexstring: "# ffe700ff")

Rif : 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

0

Swift 3.0 IOS 10.x Non capisco perché questo è così complicato, questo funziona ... Devo aver perso qualcosa ... leggerlo con attenzione, iniziare al punto 1 non 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()!) 

Usando anche questa estensione ...

extension String { 

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

    return Float(doubleValue) 
} 
} 
0

Utilizzare l'estensione UIColor seguente per convertire Stringa in Colore e viceversa.

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

}

Salva questa stringa di colore (stringWhite) per DataBase

let stringWhite = UIColor.white.toHexString() 

durante la lettura stringa di colore da utilizzare il database sottostante Codice per convertire stringWhite a UIColor

let whiteColor = UIColor(hexaDecimalString: stringWhite) 
0

Aggiungo la mia estensione, spero che tu apprezzi:

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 
    } 

} 
Problemi correlati