[英]Swift: Make an image in background of label
I want to put label into an image that is a red rectangle with corner radius (in condition that the image size must to be equal or slightly higher than the label one). 我想将标签放入带有角半径的红色矩形的图像中(条件是图像尺寸必须等于或略大于标签一个)。 For that I found a similar question .
为此,我发现了一个类似的问题 。 I tested this:
我测试了这个:
theLabel.backgroundColor = UIColor(patternImage: UIImage(named: "blah")!)
But I have problems with the image size. 但是我的图像尺寸有问题。 So I tested the second answer:
所以我测试了第二个答案:
UILabel *myLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
UIImage *img = [UIImage imageNamed:@"a.png"];
CGSize imgSize = myLabel.frame.size;
UIGraphicsBeginImageContext( imgSize );
[img drawInRect:CGRectMake(0,0,imgSize.width,imgSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
myLabel.backgroundColor = [UIColor colorWithPatternImage:newImage];
Having the last version of Xcode (Xcode 8.0) the CGRectMake
is unavailable. 没有最新版本的Xcode(Xcode 8.0),
CGRectMake
不可用。
Can anyone help me please? 谁能帮我吗?
Try this code: Tested in Swift 3. 尝试以下代码:在Swift 3中测试。
Answer 1: 答1:
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel()
label.frame = CGRect(x:0, y:0, width:imageView.frame.width , height:imageView.frame.height)
label.text = "Some Title"
label.textAlignment = .center
label.textColor = .yellow
label.font = UIFont(name: "HelveticaNeue-medium", size: CGFloat(20))
imageView.addSubview(label)
}
Output: 输出:
Answer 2: Updated 答案2:已 更新
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
imageView.layer.cornerRadius = 10
imageView.layer.masksToBounds = true
let label = UILabel()
label.frame = CGRect(x:0, y:0, width:imageView.frame.width , height:imageView.frame.height)
label.text = "Some Title"
label.textAlignment = .center
label.textColor = .yellow
label.layer.borderColor = UIColor.red.cgColor
label.layer.cornerRadius = 10
label.layer.masksToBounds = true
label.layer.borderWidth = 5
label.font = UIFont(name: "HelveticaNeue-medium", size: CGFloat(26))
imageView.addSubview(label)
}
Note: You need to workout the image size and label font size. 注意:您需要调整图像大小和标签字体大小。
Output: 输出:
Your objective c code in question is changed into swift 3.0 您的目标C代码已更改为Swift 3.0
var myLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
var img = UIImage(named:"a")
var imgSize : CGSize = myLabel.frame.size
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
myLabel.backgroundColor = UIColor(patternImage: newImage)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.