hex color from uicolor

前端 未结 4 1105
梦毁少年i
梦毁少年i 2021-01-04 08:56

i have a problem in converting uicolor to hex color, here what i found

CGColorRef colorref = [[Colorview_ backgroundColor] CGColor];

int numComponents = CG         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-04 09:39

    I tried that yesterday because I had to get a hex color from a uicolor and made it work in javascript too, but this doesn't work when a component is 0, because it gets a 0 instead of a 00. So a pure cyan would be RGB 0 255 255, and this code would return #0ffff instead of #00ffff.

    I made this code from yours, and it's working on my app:

    -(NSString*)colorToHex:(UIColor*)color{
    
        CGColorRef colorref = [color CGColor];
    
        const CGFloat *components = CGColorGetComponents(colorref);
    
        NSString *hexString = @"#";
        int hexValue = 0;
    
        for (int i=0; i<3; i++) {
            if (components[i] == 0) {
                hexString = [NSString stringWithFormat:@"%@00", hexString];
            }else{
                hexValue = 0xFF*components[i];
                hexString = [NSString stringWithFormat:@"%@%x", hexString, hexValue];
            }
        }
    
        return hexString;
    }
    

提交回复
热议问题