How can I create a UIColor from a hex string?

后端 未结 30 1703
北恋
北恋 2020-11-22 16:53

How can I create a UIColor from a hexadecimal string format, such as #00FF00?

30条回答
  •  时光说笑
    2020-11-22 17:20

    I like to ensure the alpha besides the color, so i write my own category

    + (UIColor *) colorWithHex:(int)color {
    
        float red = (color & 0xff000000) >> 24;
        float green = (color & 0x00ff0000) >> 16;
        float blue = (color & 0x0000ff00) >> 8;
        float alpha = (color & 0x000000ff);
    
        return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha/255.0];
    }
    

    easy to use like this

    [UIColor colorWithHex:0xFF0000FF]; //Red
    [UIColor colorWithHex:0x00FF00FF]; //Green
    [UIColor colorWithHex:0x00FF00FF]; //Blue
    [UIColor colorWithHex:0x0000007F]; //transparent black
    

提交回复
热议问题