Swift:在标签背景中制作图像 [英] Swift: Make an image in background of label
本文介绍了Swift:在标签背景中制作图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将标签放入带有角半径的红色矩形的图像中(条件是图像尺寸必须等于或稍大于标签一个).为此,我发现了一个类似的问题.我对此进行了测试:
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];
具有最新版本的Xcode(Xcode 8.0)的CGRectMake
不可用.
Having the last version of Xcode (Xcode 8.0) the CGRectMake
is unavailable.
有人可以帮我吗?
推荐答案
尝试以下代码:在Swift 3中测试.
Try this code: Tested in Swift 3.
答案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)
}
输出:
答案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.
输出:
这篇关于Swift:在标签背景中制作图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文