UIColor之色值设置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Maple_ROSI/article/details/52852341
  • 随机颜色,调用[UIColor randomColor];
+ (UIColor *)randomColor {
    return [UIColor colorWithRed:(CGFloat)RAND_MAX / random()
                           green:(CGFloat)RAND_MAX / random()
                            blue:(CGFloat)RAND_MAX / random()
                           alpha:1.0f];
}
  • 根据需要设置色值 [UIColor colorWithRGBHex:0xff00ff];
+ (UIColor *)colorWithRGBHex:(UInt32)hex {
    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:1.0f];
}
  • 十六进制的字符串设置[UIColor colorWithHexString:@"0xff00ff"]
// Returns a UIColor by scanning the string for a hex number and passing that to +[UIColor colorWithRGBHex:]
// Skips any leading whitespace and ignores any trailing characters
+ (UIColor *)colorWithHexString:(NSString *)stringToConvert {
    NSScanner *scanner = [NSScanner scannerWithString:stringToConvert];
    unsigned hexNum;
    if (![scanner scanHexInt:&hexNum]) return nil;
    return [UIColor colorWithRGBHex:hexNum];
}

猜你喜欢

转载自blog.csdn.net/Maple_ROSI/article/details/52852341