summaryrefslogtreecommitdiff
path: root/platform/ios/src/UIColor+MGLAdditions.mm
blob: 9ca39acda4a0816bd43caa9ef20ca7ef2bf5b87d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#import "UIColor+MGLAdditions.h"

@implementation UIColor (MGLAdditions)

- (mbgl::Color)mgl_color
{
    CGFloat r, g, b, a;
    [self getRed:&r green:&g blue:&b alpha:&a];
    return { (float)r, (float)g, (float)b, (float)a };
}

- (mbgl::style::PropertyValue<mbgl::Color>)mgl_colorPropertyValue
{
    mbgl::Color color = self.mgl_color;
    return {{ color.r, color.g, color.b, color.a }};
}

+ (UIColor *)mgl_colorWithColor:(mbgl::Color)color
{
    return [UIColor colorWithRed:color.r green:color.g blue:color.b alpha:color.a];
}

@end

@implementation NSExpression (MGLColorAdditions)

+ (NSExpression *)mgl_expressionForRGBComponents:(NSArray<NSExpression *> *)components {
    if (UIColor *color = [self mgl_colorWithRGBComponents:components]) {
        return [NSExpression expressionForConstantValue:color];
    }
    
    NSExpression *color = [NSExpression expressionForConstantValue:[UIColor class]];
    NSExpression *alpha = [NSExpression expressionForConstantValue:@1.0];
    return [NSExpression expressionForFunction:color
                                  selectorName:@"colorWithRed:green:blue:alpha:"
                                     arguments:[components arrayByAddingObject:alpha]];
}

+ (NSExpression *)mgl_expressionForRGBAComponents:(NSArray<NSExpression *> *)components {
    if (UIColor *color = [self mgl_colorWithRGBComponents:components]) {
        return [NSExpression expressionForConstantValue:color];
    }
    
    NSExpression *color = [NSExpression expressionForConstantValue:[UIColor class]];
    return [NSExpression expressionForFunction:color
                                  selectorName:@"colorWithRed:green:blue:alpha:"
                                     arguments:components];
}

+ (UIColor *)mgl_colorWithRGBComponents:(NSArray<NSExpression *> *)components {
    if (components.count < 3 || components.count > 4) {
        return nil;
    }
    
    for (NSExpression *component in components) {
        if (component.expressionType != NSConstantValueExpressionType) {
            return nil;
        }
        
        NSNumber *number = (NSNumber *)component.constantValue;
        if (![number isKindOfClass:[NSNumber class]]) {
            return nil;
        }
    }
    
    return [UIColor colorWithRed:[components[0].constantValue doubleValue] / 255.0
                           green:[components[1].constantValue doubleValue] / 255.0
                            blue:[components[2].constantValue doubleValue] / 255.0
                           alpha:components.count == 3 ? [components[3].constantValue doubleValue] : 1.0];
}

@end