如何将十六进制转换为RGB [英] how to convert hexadecimal to RGB
本文介绍了如何将十六进制转换为RGB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从十六进制转换为RGB,但十六进制处理像#FFFFFF这样的字符串。我怎么做到这一点?
I want to make a conversion from hexadecimal to RGB, but the hexadecimal deal with a string like #FFFFFF. How can I do that?
推荐答案
我刚刚为您扩展了我的UIColor类别。它就像 UIColor * green = [UIColor colorWithHexString:@#00FF00];
I've just expanded my UIColor Category for you.
use it like 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
这篇关于如何将十六进制转换为RGB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文