UILabel圆角,投影和背景图案

时间:2012-04-18 00:37:52

标签: ios uilabel calayer shadow

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

这是我带阴影的代码:

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;

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

谢谢!

1 个答案:

答案 0 :(得分:12)

enter image description here

我使用下面的代码来获得您所追求的结果。

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];