LoginSignup
3
3

More than 5 years have passed since last update.

RGBカラーコードからUIColorを生成する方法

Posted at
- (UIColor *)UIColorFromRgbCode:(NSString *)colorCode {
    int COLOR_RED   = 0;
    int COLOR_GREEN = 1;
    int COLOR_BLUE  = 2;

    if ( [[colorCode substringWithRange:NSMakeRange(0, 1)] isEqualToString:@"#"] ) {
        colorCode = [colorCode substringWithRange:NSMakeRange(1, colorCode.length - 1)];
    }
    if ( 3 == [colorCode length] ) {
        NSMutableString *_colorCode = [[[NSMutableString alloc] init] autorelease];

        for (int i = 0; i < colorCode.length; i++) {
            [_colorCode appendString:[colorCode substringWithRange:NSMakeRange(i, 1)]];
            [_colorCode appendString:[colorCode substringWithRange:NSMakeRange(i, 1)]];
        }
        colorCode = [_colorCode copy];
    }
    char *hexCode;
    char *endptr;
    float red,green,blue;
    for (int i = 0; i < 3; i++) {
        hexCode = [[NSString stringWithFormat:@"+0x%@", [colorCode substringWithRange:NSMakeRange(i * 2, 2)]] cStringUsingEncoding:NSASCIIStringEncoding];

        if (COLOR_RED == i) {
            red = strtol(hexCode, &endptr, 16);
        } else if ( COLOR_GREEN == i ) {
            green = strtol(hexCode, &endptr, 16);
        } else if ( COLOR_BLUE == i ) {
            blue = strtol(hexCode, &endptr, 16);
        }
    }

    return [UIColor colorWithRed:red / 255 green:green / 255 blue:blue / 255 alpha:1.0f];
}

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3