2010-11-24 31 views
25

我想從十六進制轉換爲RGB,但十六進制處理像#FFFFFF這樣的字符串。我怎樣才能做到這一點?如何將十六進制轉換爲RGB

+4

哪種語言? – st0le 2010-11-24 09:27:23

+0

你能指定語言嗎? – 2010-11-24 09:32:13

+0

對不起,我編輯它..它在客觀C – 2010-11-24 09:32:49

回答

81

我剛剛爲您擴展了我的UIColor類別。
使用它像UIColor *green = [UIColor colorWithHexString:@"#00FF00"];

// 
// UIColor_Categories.h 
// 
// Created by Matthias Bauch on 24.11.10. 
// Copyright 2010 Matthias Bauch. All rights reserved. 
// 

#import <Foundation/Foundation.h> 


@interface UIColor(MBCategory) 

+ (UIColor *)colorWithHex:(UInt32)col; 
+ (UIColor *)colorWithHexString:(NSString *)str; 

@end 

// 
// UIColor_Categories.m 
// 
// Created by Matthias Bauch on 24.11.10. 
// Copyright 2010 Matthias Bauch. All rights reserved. 
// 

#import "UIColor_Categories.h" 

@implementation UIColor(MBCategory) 

// takes @"#123456" 
+ (UIColor *)colorWithHexString:(NSString *)str { 
    const char *cStr = [str cStringUsingEncoding:NSASCIIStringEncoding]; 
    long x = strtol(cStr+1, NULL, 16); 
    return [UIColor colorWithHex:x]; 
} 

// takes 0x123456 
+ (UIColor *)colorWithHex:(UInt32)col { 
    unsigned char r, g, b; 
    b = col & 0xFF; 
    g = (col >> 8) & 0xFF; 
    r = (col >> 16) & 0xFF; 
    return [UIColor colorWithRed:(float)r/255.0f green:(float)g/255.0f blue:(float)b/255.0f alpha:1]; 
} 

@end 
24
//In your header file 

#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0] 

//usage 
UIColor *color = UIColorFromRGB(0x000000) 
//you can also use it inline 
[text.textField setTextColor:UIColorFromRGB(0xcccccc)]; 
3

這可以幫助你

UIColor *organizationColor = [self colorWithHexString:@"#ababab" alpha:1]; 


- (UIColor *)colorWithHexString:(NSString *)str_HEX alpha:(CGFloat)alpha_range{ 
    int red = 0; 
    int green = 0; 
    int blue = 0; 
    sscanf([str_HEX UTF8String], "#%02X%02X%02X", &red, &green, &blue); 
    return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha_range]; 
}