美文网首页
【iOS】颜色类别hex十六进制格式

【iOS】颜色类别hex十六进制格式

作者: 汴城码农 | 来源:发表于2021-09-18 17:37 被阅读0次
    #import <UIKit/UIKit.h>
    
    // 扩展UIColor类
    @interface UIColor(Extend)
    
    // 将十六进制的颜色值转为objective-c的颜色
    + (id)getColor:(NSString *) hexColor;
    
    + (id)getColor:(NSString *) hexColor alpha:(CGFloat)alpha;
    
    @end
    
    
    @implementation UIColor(Extend)
    
    + (id)getColor:(NSString *) hexColor alpha:(CGFloat)alpha
    {
        unsigned int redInt_, greenInt_, blueInt_;
        NSRange rangeNSRange_;
        rangeNSRange_.length = 2;  // 范围长度为2
        
        // 取红色的值
        rangeNSRange_.location = 0; 
        [[NSScanner scannerWithString:[hexColor substringWithRange:rangeNSRange_]] scanHexInt:&redInt_];
    
        // 取绿色的值
        rangeNSRange_.location = 2; 
        [[NSScanner scannerWithString:[hexColor substringWithRange:rangeNSRange_]] scanHexInt:&greenInt_];
        
        // 取蓝色的值
        rangeNSRange_.location = 4; 
        [[NSScanner scannerWithString:[hexColor substringWithRange:rangeNSRange_]] scanHexInt:&blueInt_];   
        
        return [UIColor colorWithRed:(float)(redInt_/255.0f) green:(float)(greenInt_/255.0f) blue:(float)(blueInt_/255.0f) alpha:alpha];
    }
    
    + (id)getColor:(NSString *) hexColor
    {
        return [self getColor:hexColor alpha:1.0f];
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:【iOS】颜色类别hex十六进制格式

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