iOS 筆記》UIColor

每次使用 UIColor 的 +colorWithRed:green:blue:alpha: 方法都要把 RGB 數值換算成 0 ~ 1.0 間的浮點數,覺得太麻煩了,可以使用下面這個方法,給一組 RGB 十進制數值的陣列:

#import <UIKit/UIKit.h>

@interface UIColor (RAMethods)
+ (UIColor *)colorWithRGB:(NSArray *)array alpha:(CGFloat)alpha;
@end
#import "UIColor+RAMethods.h"

@implementation UIColor (RAMethods)

+ (UIColor *)colorWithRGB:(NSArray *)array alpha:(CGFloat)alpha {
    if (array.count != 3) {
        return nil;
    }
    
    NSMutableArray *results = [NSMutableArray array];
    
    for (NSNumber *number in array) {
        float colorValue = ((float)[number intValue])/255;
        [results addObject:[NSNumber numberWithFloat:colorValue]];
    }

    return [self colorWithRed:[results[0] floatValue]
                        green:[results[1] floatValue]
                         blue:[results[2] floatValue]
                        alpha:alpha];
}
@end

使用方式:

#import "UIColor+RAMethods.h"

...

// R: 127, G: 127, B: 127 (灰色)
UIColor *color = [UIColor colorWithRGB:@[@127, @127, @127] alpha:1.0f];

// R:255, G: 0, B: 0 (紅色)
UIColor *color = [UIColor colorWithRGB:@[@255, @0, @0] alpha:1.0f];