ios - 使用 UILabel 文本掩码显示 UIView

标签 ios cocoa-touch uiview uilabel calayer

我正在尝试将 UIView 添加到 UILabel,这样文本就是 View 的 mask ,使我能够执行动画文本背景之类的操作(很像滑动解锁锁定屏幕上的标签)。

我计划这样做的方法是使用 View 的 layer 上的 mask 属性将其屏蔽为文本的形状。但是,我找不到将 UILabel 的文本形状作为 CALayer 的方法。

这可能吗?我只能找到覆盖 UILabel 中的 -(void)drawRect: 方法的解决方案,但这不会给我很大的灵 active 。

最佳答案

UIView added the maskView property在 iOS 8.0 中。现在,只需创建一个 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)

这将创建一个清晰的 UILabel,其中 UIColor.blueColor() 颜色取自 overlayView

关于ios - 使用 UILabel 文本掩码显示 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22671245/

相关文章:

ios - 如何在 iOS/OpenGL ES 2.0 中批处理 Sprite

iphone - 推送通知证书P12文件

ios - 如何通过名称获取属性?如果我有 `@"颜色 "`, how do I get ` self.color`?

iPhone - UIImageView 中的中心 UIImage

iphone - ARC `BAD_ACCESS` 使用 NSString 的类别方法时

iOS 使用沙盒帐户管理我的订阅

ios - "Type of expression is ambiguous without more context"在 Swift 2 中的数组初始化

iphone - iOS:如何在主视图之上显示一个小 View ?

ios - UIPageViewController 与多个 UIViewController 与标题和底栏

objective-c - 自定义 MKAnnotationView masksToBounds=YES 和 canShowCallout=YES 异常