Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set a background image as colorWithPatternImage in swift

Tags:

swift

uiview

My questions is, is it possible to have a UIView display an image, and if so, how so I do it? All I can find is the colorwithpatternImage which no longer works with swift.

The code I am trying to use now is:

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]];  

Thanks in advance for your answers!

like image 627
Mark Calhoun Avatar asked Aug 03 '14 16:08

Mark Calhoun


4 Answers

Refer to the UIColor documentation.

In Swift, you have to call a convenience initializer. This is because in Swift, all Objective-C class methods which return an instance of their class become convenience initializers.

Here's how it looks in Swift:

 self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png"))

+ (UIColor *)colorWithPatternImage:(UIImage *)image returns a UIColor instance, so it will become a convenience initializer in Swift. Similarly, UIImage imageNamed: becomes init(patternImage image: UIImage!).

like image 90
codester Avatar answered Nov 01 '22 10:11

codester


I prefer to this one:

let backgroundImage = UIImageView(frame: UIScreen.mainScreen().bounds)
backgroundImage.image = UIImage(named: "background.png")
self.view.insertSubview(backgroundImage, atIndex: 0)

Since setting image as backgroundColor would make it a litte blurry.

like image 37
DàChún Avatar answered Nov 01 '22 10:11

DàChún


Edited @User9527 's answer a bit. Not sure why it was down voted.. Worked great for me. Just added my own custom frame.

let frame = CGRectMake(10, 55, 45, 45)
let backgroundImage = UIImageView(frame: frame)
backgroundImage.image = UIImage(named: "bg_image")
self.view.insertSubview(backgroundImage, atIndex: 0)
like image 4
Dominic Smith Avatar answered Nov 01 '22 09:11

Dominic Smith


If you are trying for layer property of an imageview, u should use something like this

userProfilePic.layer.borderColor = UIColor(patternImage:UIImage(named: "yourimg.png")!).CGColor
like image 1
Suraj K Thomas Avatar answered Nov 01 '22 10:11

Suraj K Thomas