簡體   English   中英

UILabel圓角,投影和背景圖案

[英]A UILabel with rounded corners, drop shadow and background pattern

我一直在嘗試我發現的每一種方法,但我無法做到。 我只想制作一個帶圓角的標簽,一個帶背景圖案的投影。 只有當我不想要圓角時,陰影才有效。 我不能讓他們倆在一起!

這是我的陰影代碼:

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;

這段代碼確實給了我圓角但沒有陰影。 有什么建議?

謝謝!

在此輸入圖像描述

我使用下面的代碼來獲得您所追求的結果。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM