如何将十六进制转换为RGB

31

我希望将十六进制颜色值转换为RGB,但是输入的十六进制值是以字符串形式表示的,例如 #FFFFFF。请问如何完成该转换?


你能指定语言吗? - Dr Casper Black
对不起,我已经编辑了它...它是用Objective C编写的。 - R. Dewi
2
还可以看一下这些链接:https://dev59.com/n2865IYBdhLWcg3wnf9t 和 https://dev59.com/yXA75IYBdhLWcg3w8-LZ - Cody Gray
寻找一位伙伴,共同开发具有创新性的应用程序。 - Marios
请使用此链接:http://colorcode.globalmaverick.com/ - amar
4个回答

87

我为您扩展了我的 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

我知道这已经过时了,但我相信你必须要 #import <UIKit/UIColor.h> 才能真正地使用 UIColor(MBCategory),否则会出现错误提示无法找到 @interface UIColor。这可能只是因为这篇文章已经过时了,但如果没有导入,它是无法工作的。 - Popeye
它应该在由Xcode创建的标准iOS项目中工作。整个UIKit库被导入到预编译头文件(ProjectName-Prefix.pch)中。 - Matthias Bauch
这会在从long转换为无符号的UInt32时产生警告。只需将long强制转换为UInt32即可消除此警告。您永远不会得到负数,因此这样做应该是安全的。 - Guy Lowe

25
//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)]; 

2
我认为这是一件很棒的事情 :) - Munim
这个方法没有给出正确的结果。请尝试使用“#FFA300”来测试该方法。 - swiftache

5

Swift

它非常实用

extension UIColor {

    convenience init(hexString: String) {
        let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
        var int = UInt32()
        Scanner(string: hex).scanHexInt32(&int)
        let a, r, g, b: UInt32
        switch hex.count {
        case 3: // RGB (12-bit)
            (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
        case 6: // RGB (24-bit)
            (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
        case 8: // ARGB (32-bit)
            (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
        default:
            (a, r, g, b) = (1, 1, 1, 0)
        }
        self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
    }

    public func hexStringWithAlpha(_ includeAlpha: Bool) -> String {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        self.getRed(&r, green: &g, blue: &b, alpha: &a)

        if (includeAlpha) {
            return String(format: "%02X%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255))
        } else {
            return String(format: "%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255))
        }
    }

    open override var description: String {
        return self.hexStringWithAlpha(true)
    }

    open override var debugDescription: String {
        return self.hexStringWithAlpha(true)
    }
}

Obj-C

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];
}

0
根据下面的答案。对于SwiftUI,你可以这样做:
extension Color {
    init(hex: Int) {
        let red = (Double)((hex & 0xFF0000) >> 16) / 255.0
        let green = (Double)((hex & 0xFF00) >> 8) / 255.0
        let blue = (Double)((hex & 0xFF)) / 255.0

        self.init(red: red, green: green, blue: blue, opacity: 1.0)
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接