简体   繁体   English

如何在iOS中屏蔽UILabel-Objective-C

[英]How to mask a UILabel in iOS - Objective-C

I want to sub-class a UIView and place four UILabels over top one another ; 我想子类化一个UIView并将四个UILabel放在另一个之上; top label will be the MASK, 2nd label will be a normal label with text, the 3rd label is a label with solid background with no text. 最上面的标签是遮罩,第二个标签是带有文本的普通标签,第三个标签是带有纯背景且没有文本的标签。 the bottom label will the same as the top 2nd label with a different color font. 底部标签将与顶部第二标签相同,但颜色字体不同。 when i sent the width of the third label it will cover up the bottom label showing a partial view of the text. 当我发送第三个标签的宽度时,它将覆盖底部的标签,显示文本的部分视图。 I want to have the 2nd text be one color while the uncoverd bottom label display another color font. 我想让第二个文本是一种颜色,而未覆盖的底部标签显示另一种颜色的字体。

Is this possibe? 这是可能吗? If someone can explain how to mask in objective-C that will help too. 如果有人可以解释如何在Objective-C中掩盖这也将有所帮助。

I trying to build a UIView that acts like a progress bar, as the bar fill to 60%, I want to top text to show in white font color, when the bottom text shows in a different color. 我试图构建一个像进度条一样的UIView,当进度条填充到60%时,我想让顶部文本以白色字体显示,而底部文本以其他颜色显示。

You could do it with two UILabels, one on the bottom, and one embedded in another view on top. 您可以使用两个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];

Then, when you want to change the progress, you'd set the width of topContainer . 然后,当您想更改进度时,可以设置topContainer的宽度。 This should clip topLabel . 这应该剪辑topLabel

Rather than using four UILabels, why not subclass UILabel and draw it yourself in the drawRect: method? 而不是使用四个UILabel,为什么不继承UILabel并在drawRect:方法中自己绘制呢? It would look something like: 它看起来像:

- (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];
}

You could make the masking image and the alternate font properties of your subclass, for convenience. 为了方便起见,您可以制作遮罩图像和子类的替代字体属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM