【问题标题】:How to mask a UILabel in iOS - Objective-C如何在 iOS 中屏蔽 UILabel - Objective-C
【发布时间】:2011-06-27 22:10:59
【问题描述】:

我想继承一个 UIView 并将四个 UILabel 放在另一个上面;顶部标签将是 MASK,第二个标签将是带有文本的普通标签,第三个标签是没有文本的纯色背景标签。底部标签将与顶部第二个标签相同,但颜色字体不同。当我发送第三个标签的宽度时,它将覆盖底部标签,显示文本的部分视图。我想让第二个文本是一种颜色,而未覆盖的底部标签显示另一种颜色字体。

这可能吗?如果有人可以解释如何在 Objective-C 中进行掩码,那也会有所帮助。

我尝试构建一个类似于进度条的 UIView,当进度条填充到 60% 时,我希望顶部文本以白色字体颜色显示,而底部文本以不同颜色显示。

【问题讨论】:

  • 我有点让它通过使用 UILineBreakModeClip 并将标签放在彼此之上来工作。但是 Clip 似乎丢掉了最后一个字母;我认为它应该剪辑在矩形结束的地方。我想渲染一半的“W”

标签: objective-c ios masking


【解决方案1】:

与其使用四个 UILabel,为什么不继承 UILabel 并在drawRect: 方法中自己绘制呢?它看起来像:

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    // Set the mask
    CGContextClipToMask(context, self.bounds, /* mask image */);

    // Draw the text in a different font
    [self.text drawInRect:rect withFont:/* alternate font */];

    // Draw a solid background
    CGContextSetRGBFillColor(context, ...);
    CGContextFillRect(context, rect);

    // Draw the text normally
    [super drawRect:rect];
}

为方便起见,您可以制作子类的遮罩图像和备用字体属性。

【讨论】:

  • 这会允许部分字符渲染吗?目标是确保如果进度条位于角色之间,则该角色应显示两种颜色。
  • 你可能想在 CGContextClipToMask 中使用 self.bounds,而不是 self.frame。
  • @titaniumdecoy 感谢您的理解,已修复。
【解决方案2】:

您可以使用两个 UILabel 来做到这一点,一个在底部,一个嵌入在另一个视图中。

UILabel *bottomLabel = ...;
[self.view addSubview:bottomLabel];

UIView *topContainer = [[UIView alloc] initWithFrame:bottomLabel.frame];
topContainer.clipsToBounds = YES;
topContainer.opaque = NO;
topContainer.backgroundColor = [UIColor clearColor];

UILabel *topLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, bottomLabel.frame.size.width, bottomLabel.frame.size.height)];
topLabel.text = bottomLabel.text;
topLabel.opaque = NO;
topLabel.backgroundColor = [UIColor clearColor];

[topContainer addSubview:topLabel];
[self.view addSubview:topContainer];

然后,当您想要更改进度时,您可以设置topContainer 的宽度。这应该剪辑topLabel

【讨论】:

  • 这会允许部分字符渲染吗?目标是确保如果进度条位于角色之间,则该角色应显示两种颜色
  • 是的。这应该可行,因为您将调整父 UIView 而不是 UILabel 的大小。
  • 按我的意愿工作。谢谢。
猜你喜欢
  • 2012-07-15
  • 2011-06-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-10
  • 2010-12-17
  • 1970-01-01
  • 1970-01-01
  • 2016-10-16
相关资源
最近更新 更多