[英]Display UIView with a UILabel text mask
我正在尝试将UIView
添加到UILabel
,以使文本成为视图的蒙版,使我能够执行诸如动画文本背景(类似于在锁定屏幕上解锁标签的幻灯片)之类的操作。
我打算这样做的方法是使用视图layer
上的mask
属性将其蒙版为文本形状。 但是,我找不到一种将UILabel
的文本形状作为CALayer
。
这有可能吗? 我只能在UILabel
找到覆盖-(void)drawRect:
方法的解决方案,但这不会给我太大的灵活性。
UIView
在iOS 8.0中添加了maskView
属性 。 现在,只需创建一个UILabel
用作UIView
的蒙版:
目标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];
迅捷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)
这将创建一个清晰的UILabel
,其UIColor.blueColor()
颜色取自overlayView
。
如果您针对iOS 8+进行构建, mopsled的解决方案将更加灵活。 但是,如果您正在寻找iOS 8之前的答案,请按此处。
感谢Linuxios向我指出了这个问题 。 关键是使用CATextLayer
而不是UILabel
。
目标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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.