Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

ios - Display UIView with a UILabel text mask

I'm trying to add a UIView to a UILabel, so that the text is the view's mask, enabling me to do things like animated text backgrounds (much like the slide to unlock label on the lockscreen).

The way I was planning on doing it was using the mask property on the view's layer to mask it to the shape of the text. However, I cannot find a way to get the UILabel's text shape as a CALayer.

Is this even possible? I can only find solutions that override the -(void)drawRect: method in the UILabel, but this wouldn't give me much flexibility.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

UIView added the maskView property in iOS 8.0. Now, just create a UILabel to use as a mask for a 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)

This creates a crisp UILabel with UIColor.blueColor() color taken from overlayView.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...