为了便于日常开发效率,因此创建了一些小的工具类便于使用.
具体 code 如下:
声明:
/*
为控件设置色值
*/
#import <UIKit/UIKit.h>
@interface UIColor (FYH)
/**
根据RGB颜色值生成UIColor
@param rgbValue 颜色值
@param alpha 透明度(0-1)之间
@return 结果样式
*/
+ (UIColor *)colorFromRGB:(NSInteger)rgbValue withAlpha:(CGFloat)alpha;
+ (UIColor *)colorFromRGB:(NSInteger)rgbValue;
/**
根据十六进制颜色值生成UIColor
@param hexString 十六进制色值
@return 结果样式
*/
+ (UIColor *)colorWithHexString:(NSString *)hexString;
/**
根据十六进制颜色值生成UIColor
@param hexString 十六进制色值
@param alpha 透明度(0-1)之间
@return 结果样式
*/
+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha;
+ (UIColor *)colorWithHexStringWithAlpha:(NSString *)hexString;
@end
实现:
#import "UIColor+FYH.h"
@implementation UIColor (FYH)
+ (UIColor *)colorFromRGB:(NSInteger)rgbValue withAlpha:(CGFloat)alpha {
return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16)) / 255.0
green:((float)((rgbValue & 0xFF00) >> 8)) / 255.0
blue:((float)(rgbValue & 0xFF)) / 255.0 alpha:alpha];
}
+ (UIColor *)colorFromRGB:(NSInteger)rgbValue {
return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16)) / 255.0
green:((float)((rgbValue & 0xFF00) >> 8)) / 255.0
blue:((float)(rgbValue & 0xFF)) / 255.0 alpha:1.0];
}
/**
* hexString eg. #ff0000
*/
+ (UIColor *)colorWithHexString:(NSString *)hexString {
return [UIColor colorWithHexString:hexString alpha:1.0];
}
/**
* hexString eg. #ffffffff
*/
+ (UIColor *)colorWithHexStringWithAlpha:(NSString*)hexString {
if ([hexString hasPrefix:@"0x"] || [hexString hasPrefix:@"0X"]) {
hexString = [hexString substringFromIndex:2];
} else if ([hexString hasPrefix:@"#"]) {
hexString = [hexString substringFromIndex:1];
}
unsigned int value = 0;
BOOL flag = [[NSScanner scannerWithString:hexString] scanHexInt:&value];
if(NO == flag)
return [UIColor clearColor];
float r, g, b, a;
a = (value & 0x000000FF) / 255.0;
value = value >> 8;
b = value & 0x000000FF;
value = value >> 8;
g = value & 0x000000FF;
value = value >> 8;
r = value;
return [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a];
}
+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha {
if ([hexString hasPrefix:@"0x"] || [hexString hasPrefix:@"0X"]) {
hexString = [hexString substringFromIndex:2];
} else if ([hexString hasPrefix:@"#"]) {
hexString = [hexString substringFromIndex:1];
}
unsigned int value = 0;
BOOL flag = [[NSScanner scannerWithString:hexString] scanHexInt:&value];
if(NO == flag)
return [UIColor clearColor];
float r, g, b, a;
a = alpha;
b = value & 0x0000FF;
value = value >> 8;
g = value & 0x0000FF;
value = value >> 8;
r = value;
return [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a];
}
@end
以上便是此次分享的内容,期待大神多多指点补充,使其更加强壮!
网友评论