UILabel:背景依赖的颜色

Nic*_*tto 22 colors objective-c uilabel ios

我试图寻找这个问题的解决方案,但我甚至无法用正确的方式说出来.

基本上我有一个在操作过程中充满颜色的条形图.我有一个标签,其进度百分比具有相同颜色的填充颜色,所以我需要在填充颜色在背面时进行更改.像这样的东西:

在此输入图像描述

无论如何都可以实现这个结果吗?万一,怎么样?

Mor*_*ast 7

最简单的方法是创建一个UIView具有progress属性和覆盖的子类-drawRect:.

您需要的所有代码是:

- (void)drawRect:(CGRect)rect {

    CGContextRef context = UIGraphicsGetCurrentContext();

    // Set up environment.
    CGSize size = [self bounds].size;
    UIColor *backgroundColor = [UIColor colorWithRed:108.0/255.0 green:200.0/255.0 blue:226.0/255.0 alpha:1.0];
    UIColor *foregroundColor = [UIColor whiteColor];
    UIFont *font = [UIFont boldSystemFontOfSize:42.0];

    // Prepare progress as a string.
    NSString *progress = [NSString stringWithFormat:@"%d%%", (int)round([self progress] * 100)];
    NSMutableDictionary *attributes = [@{ NSFontAttributeName : font } mutableCopy];
    CGSize textSize = [progress sizeWithAttributes:attributes];
    CGFloat progressX = ceil([self progress] * size.width);
    CGPoint textPoint = CGPointMake(ceil((size.width - textSize.width) / 2.0), ceil((size.height - textSize.height) / 2.0));

    // Draw background + foreground text
    [backgroundColor setFill];
    CGContextFillRect(context, [self bounds]);
    attributes[NSForegroundColorAttributeName] = foregroundColor;
    [progress drawAtPoint:textPoint withAttributes:attributes];

    // Clip the drawing that follows to the remaining progress' frame.
    CGContextSaveGState(context);
    CGRect remainingProgressRect = CGRectMake(progressX, 0.0, size.width - progressX, size.height);
    CGContextAddRect(context, remainingProgressRect);
    CGContextClip(context);

    // Draw again with inverted colors.
    [foregroundColor setFill];
    CGContextFillRect(context, [self bounds]);
    attributes[NSForegroundColorAttributeName] = backgroundColor;
    [progress drawAtPoint:textPoint withAttributes:attributes];

    CGContextRestoreGState(context);
}

- (void)setProgress:(CGFloat)progress {
    _progress = fminf(1.0, fmaxf(progress, 0.0));
    [self setNeedsDisplay];
}
Run Code Online (Sandbox Code Playgroud)

您可以根据需要使用背景颜色,文本颜色,字体等属性展开类.