gpt4 book ai didi

ios - Swift:在标签背景中制作图像

转载 作者:可可西里 更新时间:2023-11-01 00:58:09 24 4
gpt4 key购买 nike

我想将标签放入一个带有圆角半径的红色矩形的图像中(条件是图像尺寸必须等于或略大于标签尺寸)。为此,我找到了一个类似的 question .我测试了这个:

theLabel.backgroundColor = UIColor(patternImage: UIImage(named: "blah")!)

但是我对图像大小有疑问。所以我测试了第二个答案:

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 不可用。

谁能帮帮我?

最佳答案

试试这个代码:在 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)
}

输出:

enter image description here

答案 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)
}

注意:您需要调整图像大小和标签字体大小。

输出:

enter image description here

关于ios - Swift:在标签背景中制作图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40379082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com