iOS开发_修改颜色Color

  • UIColor+Modify.h

#import <UIKit/UIKit.h>

@interface UIColor (Modify)

/**
 * @brief 反转颜色
 *
 * @return 反转处理后的颜色
 */
- (UIColor *)inverted;

/**
 * @brief 半透明颜色
 *
 * @return 半透明处理后的颜色
 */
- (UIColor *)translucence;

/**
 * @brief 使明亮颜色
 *
 * @return 使明亮处理后的颜色
 */
- (UIColor *)lighten:(CGFloat)lighten;

/**
 * @brief 使变暗颜色
 *
 * @return 使变暗处理后的颜色
 */
- (UIColor *)darken:(CGFloat)darken;

@end
  • UIColor+Modify.m

#import "UIColor+Modify.h"

@implementation UIColor (Modify)

/**
 * @brief 反转颜色
 *
 * @return 反转处理后的颜色
 */
- (UIColor *)inverted {
    NSArray *components = [self component_array];
    return [UIColor colorWithRed:1-[components[0] doubleValue] green:1-[components[1] doubleValue] blue:1-[components[2] doubleValue] alpha:[components[3] doubleValue]];
}

/**
 * @brief 半透明颜色
 *
 * @return 半透明处理后的颜色
 */
- (UIColor *)translucence {
    CGFloat hue = 0, saturation = 0, brightness = 0, alpha = 0;
    [self getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
    return [UIColor colorWithHue:hue saturation:saturation*1.158 brightness:brightness*0.95 alpha:alpha];
}

/**
 * @brief 使明亮颜色
 *
 * @return 使明亮处理后的颜色
 */
- (UIColor *)lighten:(CGFloat)lighten {
    CGFloat hue = 0, saturation = 0, brightness = 0, alpha = 0;
    [self getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
    return [UIColor colorWithHue:hue saturation:saturation*(1-lighten) brightness:brightness*(1+lighten) alpha:alpha];
}

/**
 * @brief 使变暗颜色
 *
 * @return 使变暗处理后的颜色
 */
- (UIColor *)darken:(CGFloat)darken {
    CGFloat hue = 0, saturation = 0, brightness = 0, alpha = 0;
    [self getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
    return [UIColor colorWithHue:hue saturation:saturation*(1+darken) brightness:brightness*(1-darken) alpha:alpha];
}

/**
 * @brief 颜色组合
 *
 * @return 颜色组合
 */
- (NSArray *)component_array {
    CGFloat red, green, blue, alpha;
    const CGFloat *components = CGColorGetComponents([self CGColor]);
    if (CGColorGetNumberOfComponents([self CGColor]) == 2) {
        red = components[0];
        green = components[0];
        blue = components[0];
        alpha = components[1];
    }
    else {
        red = components[0];
        green = components[1];
        blue = components[2];
        alpha = components[3];
    }
    return @[@(red), @(green), @(blue), @(alpha)];
}

@end

posted @ 2022-12-08 17:36  CH520  阅读(77)  评论(0编辑  收藏  举报