ios - UILabel:背景相关颜色

标签 ios objective-c colors uilabel

我试图寻找这个问题的解决方案,但我什至无法用我猜的文字正确地表达它。

基本上,我有一个在操作进行时会填充颜色的栏。我有一个进度百分比的标签,其颜色与填充颜色相同,因此当填充颜色位于背面时我需要更改它。像这样的事情:

enter image description here

有可能达到这个结果吗?万一怎么办?

最佳答案

最简单的方法是创建一个 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];
}

您可以根据需要使用背景颜色、文本颜色、字体等属性扩展该类。

关于ios - UILabel:背景相关颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46046682/

相关文章:

ios - 线程 1 EXC_BREAKPOINT(代码=1,子代码=0x101959bfc)Swift

ios - 如何创建自己的完成处理程序作为方法参数的一部分

delphi - 在 Delphi 中初始程序加载后更改一个 TStatusPanel 的颜色?

objective-c - Xcode:如何访问子类中的方法?

python - matplotlib 颜色图

html - CSS 以两种颜色显示一个字符

ios - 我可以将对象图保存到 CloudKit 吗?

iphone - iOS StoreKit 旧版/升级支持的最佳实践是什么?

ios - 同时滚动和捏合多个 UiScrollView

objective-c - 当没有其他引用保留对象时,如何安全地将 id 对象存储在 ARC 下的 C++ void* 成员中?