微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ios – 带圆角,投影和背景图案的UILabel

我一直在尝试我发现的每一种方法,但我无法做到.我只想制作一个带圆角的标签,一个带背景图案的投影.只有当我不想要圆角时,阴影才有效.我不能把它们放在一起!

这是我带阴影的代码

label.text = msg;
label.textAlignment = UITextAlignmentCenter;
label.frame = CGRectMake(20,10,280,40);
label.backgroundColor 
    = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"msg_Box_bg.png"]];

[label.layer setCornerRadius:10];
[label.layer setMasksToBounds:NO];

/* Shadow */
label.layer.shadowColor = [UIColor blackColor].CGColor;
label.layer.shadowOpacity = 0.6;
label.layer.shadowOffset = CGSizeMake(0,0);
label.layer.shadowRadius = 3;

这给了我没有圆角的阴影.但是,如果我使用

[label.layer setMasksToBounds:YES];

这将给我圆角,没有阴影.我已经建议使用阴影路径,所以带阴影路径的代码如下所示:

label.text = msg;
label.textAlignment = UITextAlignmentCenter;
label.frame = CGRectMake(20,40);
label.backgroundColor 
    = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"msg_Box_bg.png"]];

[label.layer setCornerRadius:10];
[label.layer setMasksToBounds:YES];

/* Shadow */
label.layer.shadowColor = [UIColor blackColor].CGColor;
label.layer.shadowOpacity = 0.6;
label.layer.shadowOffset = CGSizeMake(0,0);
label.layer.shadowRadius = 3;
label.layer.shadowPath = [[UIBezierPath bezierPathWithRoundedRect:label.frame cornerRadius:10]CGPath];
label.layer.shouldRasterize = YES;

这段代码确实给了我圆角但没有阴影.
有什么建议?

谢谢!

解决方法

我使用下面的代码来获得您所追求的结果.
CGSize size = CGSizeMake(280,40);

/** Shadow */
CALayer *shadowLayer = [CALayer new];
shadowLayer.frame = CGRectMake(20,100,size.width,size.height);
shadowLayer.cornerRadius = 10;

shadowLayer.backgroundColor = [UIColor clearColor].CGColor; 
shadowLayer.shadowColor = [UIColor blackColor].CGColor;
shadowLayer.shadowOpacity = 0.6;
shadowLayer.shadowOffset = CGSizeMake(0,0);
shadowLayer.shadowRadius = 3;

/** Label */
UILabel *label = [UILabel new];
label.text = @"Hello World";
label.textAlignment = UITextAlignmentCenter;
label.frame = CGRectMake(0,size.height);
label.backgroundColor = [UIColor clearColor]; 
label.layer.cornerRadius = 10;
[label.layer setMasksToBounds:YES];
//  customLabel.backgroundColor = [UIColor whiteColor]; 
label.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"options.png"]];

/** Add the Label to the shawdow layer */
[shadowLayer addSublayer:label.layer];

[self.view.layer addSublayer:shadowLayer];      

[shadowLayer release];

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐