iOS小记--UIColor反转

今天脑洞一开,想起UIColor既然可以用HEX data(0xFFFFFF)去设置,那我可不可以取个反色,这样就可以实现某些控件的文字和背景协调变化了;越想越激动,于是开干。

    1. 从UIColor读取颜色值。方法如下,在UIColor.h的头文件里可以找到。一开始我还没注意到,从这篇文章看到了方法。
    CGFloat red, green, blue, alpha;
    BOOL got = [self getRed:&red green:&green blue:&blue alpha:&alpha];
    1. 生成反转的新的Color。注意这里的alpha不建议取反,因为大多数时候选用的颜色都是alpha==1,你取反那不就抓瞎了呢。
    UIColor *antitheticColor = [UIColor colorWithRed:1-red green:1-green blue:1-blue alpha:alpha];
    1. 贴一下代码,我这里是为了实现PickerView的背景色和textColor的联动。
// IVPickerView.m
- (void)setBackgroundColor:(UIColor *)backgroundColor {
    [super setBackgroundColor:backgroundColor];
    [self setCountTextColor:[backgroundColor antitheticColor]];
}

- (void)setCountTextColor:(UIColor *)color {
    _antitheticColor = color;
    if (self.countPicker) {
        [self.countPicker reloadAllComponents];
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView
            viewForRow:(NSInteger)row
          forComponent:(NSInteger)component
           reusingView:(UIView *)view {
    ...
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, width, FONT(40))];
    label.textColor = _antitheticColor;
    ...
    return view;
}


// UIColor+Utils.m
- (UIColor *)antitheticColor {
    CGFloat red, green, blue, alpha;
    BOOL got = [self getRed:&red green:&green blue:&blue alpha:&alpha];
    if (!got) {
        return [UIColor whiteColor];
    }
    UIColor *antitheticColor = [UIColor colorWithRed:1-red green:1-green blue:1-blue alpha:alpha];
    return antitheticColor;
}

- (BOOL)isSameColor:(UIColor *)color {
    if (CGColorEqualToColor(self.CGColor, color.CGColor)) {
        return YES;
    }
    return NO;
}

你可能感兴趣的:(iOS小记--UIColor反转)