objective-c - 如何将十六进制转换为RGB

标签 objective-c ios cocoa-touch hex rgb

我想将十六进制转换为 RGB,但十六进制处理像 #FFFFFF 这样的字符串。我该怎么做?

最佳答案

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

关于objective-c - 如何将十六进制转换为RGB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4265161/

相关文章:

objective-c - NSTextView 在文本之间插入图像

objective-c - 哈希表中的 ARC 弱引用

ios - NSMutableURLRequest 和 JSON - 我将如何完成此连接?

ios - UIView 动画问题 swift 4 Xcode9

ios - 在自定义 UIView 中动画化 UIBezierPath 不起作用

iphone - iPhone 上的自定义 UITabBarItem 图像/标题

ios:用返回替换 NSString 中的单词

ios - 无法通过 remotebuild 和 Visual Studio 2015 构建/调试 iOS Cordova 应用程序

cocoa-touch - cocoa touch : How to detect a missing file on the download server

ios - UITableViewCell 重新排序 : cell stops moving 10 pixels into the drag