用UILabel文本掩码显示UIView

我试图添加一个UIView到一个UILabel ,以便文本是视图的面具,使我能够做像animation文本背景的东西(很像幻灯片解锁锁屏上的标签)。

我打算这样做的方式是在视图的layer上使用mask属性来将其掩盖为文本的形状。 但是,我无法find一种方式来获得UILabelCALayer文本形状。

这甚至有可能吗? 我只能find覆盖UILabel-(void)drawRect:方法的解决scheme,但是这不会给我太大的灵活性。

UIView在iOS 8.0中添加了maskView属性 。 现在,创build一个UILabel作为UIView的掩码:

Objective-C的:

 UILabel* label = [[UILabel alloc] initWithFrame:self.view.frame]; label.text = @"Label Text"; label.font = [UIFont systemFontOfSize:70]; label.textAlignment = NSTextAlignmentCenter; label.textColor = [UIColor whiteColor]; UIView* overlayView = [[UIView alloc] initWithFrame:self.view.frame]; overlayView.backgroundColor = [UIColor blueColor]; overlayView.maskView = label; [self.view addSubview:overlayView]; 

Swift 2

 let label = UILabel.init(frame: view.frame) label.text = "Label Text" label.font = UIFont.systemFontOfSize(70) label.textAlignment = .Center label.textColor = UIColor.whiteColor() let overlayView = UIView.init(frame: view.frame) overlayView.backgroundColor = UIColor.blueColor() overlayView.maskView = label view.addSubview(overlayView) 

这将创build一个清晰的UILabel其中UIColor.blueColor()overlayView获取的UIColor.blueColor()颜色。

如果您为iOS 8+构build, mopsled的解决scheme更加灵活。 但是,如果您正在寻找iOS 8以前的答案,那么就是这样。


感谢Linuxios指出我这个问题 。 关键是使用CATextLayer而不是UILabel

Objective-C的:

 CGRect textRect = {0, 100, self.view.frame.size.width, 100}; // rect to display the view in CATextLayer* textMask = [CATextLayer layer]; textMask.contentsScale = [UIScreen mainScreen].scale; // sets the layer's scale to the main screen scale textMask.frame = (CGRect){CGPointZero, textRect.size}; textMask.foregroundColor = [UIColor whiteColor].CGColor; // an opaque color so that the mask covers the text textMask.string = @"Text Mask"; // your text here textMask.font = (__bridge CFTypeRef _Nullable)([UIFont systemFontOfSize:30]); // your font here textMask.alignmentMode = kCAAlignmentCenter; // centered text UIView* view = [[UIView alloc] initWithFrame:textRect]; view.backgroundColor = [UIColor blueColor]; view.layer.mask = textMask; // mask the view to the textMask [self.view addSubview:view]; 

迅速:

 let textRect = CGRect(x: 0, y: 100, width: view.frame.size.width, height: 100) // rect to display the view in let textMask = CATextLayer() textMask.contentsScale = UIScreen.mainScreen().scale // sets the layer's scale to the main screen scale textMask.frame = CGRect(origin: CGPointZero, size: textRect.size) textMask.foregroundColor = UIColor.whiteColor().CGColor // an opaque color so that the mask covers the text textMask.string = "Text Mask" // your text here textMask.font = UIFont.systemFontOfSize(30) // your font here textMask.alignmentMode = kCAAlignmentCenter // centered text let bgView = UIView(frame: textRect) bgView.backgroundColor = UIColor.blueColor() bgView.layer.mask = textMask // mask the view to the textMask view.addSubview(bgView) 

我创build了自定义的maskLabel。

检查答案https://stackoverflow.com/a/47105664/7371852

这是结果。 在这里输入图像说明