iOS 十六进制颜色

作者: Jixin | 来源:发表于2016-08-31 15:55 被阅读156次

开发时,使用颜色的时候都是用的RGB颜色,但是UI设计师提供的颜色值一般都是十六进制的,转换起来非常麻烦。
我对UIColor做了扩展,可以直接使用十六进制格式的颜色。

一、主要步骤

1.对UIColor使用Category(类别)

  • 此处只需要对UIColor扩充方法,并不需要扩充成员变量和属性,所以只需要使用Category,不需要使用Extension。
  • Category最显著的特征就是小括号中有名字,而且文件名中有“+”,如:UIColor+Tool.h和UIColor+Tool.m
setp1.png setp2.png

2.使用十六进制颜色的类方法

(1)UIColor+Tool.h中

#import <UIKit/UIKit.h>

@interface UIColor (Tool)

/**
 *  16进制转换成UIColor
 *
 *  @param hex
 *
 *  @return UIColor
 */
+ (UIColor *)colorWithRGBHex:(UInt32)hex;

/**
 *  16进制转换成UIColor,带透明度
 *
 *  @param hex   十六进制颜色   eg. 0x8b8b8e
 *  @param alpha 透明度        取值 0-1.0
 *
 *  @return UIColor
 */
+ (UIColor *)colorWithRGBHex:(UInt32)hex alpha:(CGFloat)alpha;

@end

(2)UIColor+Tool.m中

#import "UIColor+Tool.h"

@implementation UIColor (Tool)

//16进制转换成UIColor
+ (UIColor *)colorWithRGBHex:(UInt32)hex {
    return [UIColor colorWithRGBHex:hex alpha:1.0f];
}

+ (UIColor *)colorWithRGBHex:(UInt32)hex alpha:(CGFloat)alpha {
    int r = (hex >> 16) & 0xFF;
    int g = (hex >> 8) & 0xFF;
    int b = (hex) & 0xFF;
    return [UIColor colorWithRed:r / 255.0f green:g / 255.0f blue:b / 255.0f alpha:alpha];
}

@end

二、使用

1.

#import "UIColor+Tool.h"

2.

UIColor *backgroundColor = [UIColor colorWithRGBHex:0xF83838];

UIColor *viewColor = [UIColor colorWithRGBHex:0xF83838 alpha:0.8f];

三、更加简单粗暴的方法

直接用宏定义,我更喜欢使用宏定义的方式

//十六进制色值
#define kUIColorFromRGB(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]

//十六进制色值,有透明度
#define kUIColorFromRGBWithTransparent(rgbValue,transparentValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:transparentValue]

相关文章

网友评论

    本文标题:iOS 十六进制颜色

    本文链接:https://www.haomeiwen.com/subject/xngqettx.html