简体   繁体   中英

Cant convert string hex into hexint and then into UIColor

I have JSON Data with an array of strings. When I decode this data I need to convert strings into ints and then use it for creating UIColors. But when I convert my hexadecimal from string to int it returns me the wrong color. Here the code

struct DrawingElement {
    let colorsForCells: [UIColor]
}

extension DrawingElement: Decodable {
    
    enum CodingKeys: String, CodingKey {
        case colorsForCells = "cells"
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        let rawColors = try container.decode([String].self, forKey: .colorsForCells)
        colorsForCells = rawColors.map {
            
            let value = Int($0)
            let color = uiColorFromHex(rgbValue: value ?? 77)
            return color == .black ? .white : color
            
        }
    }
   
}
func uiColorFromHex(rgbValue: Int) -> UIColor {
    
    let red =   CGFloat((rgbValue & 0xFF0000) >> 16) / 0xFF
    let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 0xFF
    let blue =  CGFloat(rgbValue & 0x0000FF) / 0xFF
    let alpha = CGFloat(1.0)
    
    return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}

Example of my string in Data: "0xe7c79d"

You have to remove the 0x prefix and then specify the radix 16:

let s = "0xe7c79d"
print(Int(s)) // nil

let value = s.hasPrefix("0x")
    ? String(s.dropFirst(2))
    : s
print(Int(value, radix: 16)) // 15189917

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM