9

我一直在尝试我找到的每一种方法,但我无法做到。我只想制作一个带有圆角的标签,一个带有背景图案的阴影。只有当我不想要圆角时,阴影才有效。我不能让他们两个在一起!

这是我的阴影代码:

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,10,280,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;

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

谢谢!

4

1 回答 1

12

在此处输入图像描述

我使用下面的代码来获得您想要的结果。

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, 0, size.width, 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];
于 2012-04-20T05:09:38.207 回答