ios中十六進(jìn)制的顏色轉(zhuǎn)換為uicolor

字號(hào):


    可用類別寫一個(gè) 方便使用
    + (uicolor *) colorwithhexstring: (nsstring *)color
    {
    nsstring *cstring = [[colorstringbytrimmingcharactersinset:[nscharactersetwhitespaceandnewlinecharacterset]] uppercasestring];
    // string should be 6 or 8 characters
    if ([cstring length] <6) {
    return [uicolorclearcolor];
    }
    // strip 0x if it appears
    if ([cstring hasprefix:@0x])
    cstring = [cstringsubstringfromindex:2];
    if ([cstring hasprefix:@#])
    cstring = [cstringsubstringfromindex:1];
    if ([cstring length] !=6)
    return [uicolorclearcolor];
    // separate into r, g, b substrings
    nsrange range;
    range.location =0;
    range.length =2;
    //r
    nsstring *rstring = [cstring substringwithrange:range];
    //g
    range.location =2;
    nsstring *gstring = [cstring substringwithrange:range];
    //b
    range.location =4;
    nsstring *bstring = [cstring substringwithrange:range];
    // scan values
    unsigned int r, g, b;
    [[nsscannerscannerwithstring:rstring] scanhexint:&r];
    [[nsscannerscannerwithstring:gstring] scanhexint:&g];
    [[nsscannerscannerwithstring:bstring] scanhexint:&b];
    return [uicolorcolorwithred:((float) r /255.0f) green:((float) g /255.0f) blue:((float) b /255.0f) alpha:1.0f];
    }