Reputation: 1550
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.
Can anyone help me please?
Upvotes: 2
Views: 6213
Reputation: 8986
Try this code: Tested in Swift 3.
Answer 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
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:
Upvotes: 3
Reputation: 5268
Your objective c code in question is changed into 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)
Upvotes: 0