首页 > 代码库 > 颜色常识
颜色常识
#import "ViewController.h"#import "UIColor+Hex.h"#define XMGColor(r,g,b) [UIColor colorWithRed:(r) / 256.0 green:(g) / 256.0 blue:(b) / 256.0 alpha:1]@interface ViewController ()@property (weak, nonatomic) IBOutlet UILabel *labelView;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIColor *color = [UIColor colorWithRed:213 / 255.0 green:213 / 255.0 blue:213 / 255.0 alpha:1]; _labelView.textColor = [UIColor colorWithHexString:@"eb3535"];// _labelView.textColor = XMGColor(255 , 255, 255);}/* 颜色:3种颜色通道 R G B 颜色表达方式 24位 32位 每一个颜色通道是8位,0~256 R:213 G:213 B:213 #ffffff R:FF => 10进制 255 G:FF 255 B:FF 255 #:美工16进制表示形式 0x:OC16进制表达式 */- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}@end
UIColor+Hex.h
#import <UIKit/UIKit.h>@interface UIColor (Hex)// 默认alpha位1+ (UIColor *)colorWithHexString:(NSString *)color;//从十六进制字符串获取颜色,//color:支持@“#123456”、 @“0X123456”、 @“123456”三种格式+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha;@end
UIColor+Hex.m
#import "UIColor+Hex.h"@implementation UIColor (Hex)+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha{ //删除字符串中的空格 NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString]; // String should be 6 or 8 characters if ([cString length] < 6) { return [UIColor clearColor]; } // strip 0X if it appears //如果是0x开头的,那么截取字符串,字符串从索引为2的位置开始,一直到末尾 if ([cString hasPrefix:@"0X"]) { cString = [cString substringFromIndex:2]; } //如果是#开头的,那么截取字符串,字符串从索引为1的位置开始,一直到末尾 if ([cString hasPrefix:@"#"]) { cString = [cString substringFromIndex:1]; } if ([cString length] != 6) { return [UIColor clearColor]; } // Separate into r, g, b substrings NSRange range; range.location = 0; range.length = 2; //r NSString *rString = [cString substringWithRange:range]; //g range.location = 2; NSString *gString = [cString substringWithRange:range]; //b range.location = 4; NSString *bString = [cString substringWithRange:range]; // Scan values unsigned int r, g, b; [[NSScanner scannerWithString:rString] scanHexInt:&r]; [[NSScanner scannerWithString:gString] scanHexInt:&g]; [[NSScanner scannerWithString:bString] scanHexInt:&b]; return [UIColor colorWithRed:((float)r / 255.0f) green:((float)g / 255.0f) blue:((float)b / 255.0f) alpha:alpha];}//默认alpha值为1+ (UIColor *)colorWithHexString:(NSString *)color{ return [self colorWithHexString:color alpha:1.0f];}@end
颜色常识
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。