how to set a background image as colorWithPatternImage in swift

安稳与你 提交于 2020-01-10 06:48:08

问题


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!


回答1:


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!).




回答2:


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.




回答3:


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)



回答4:


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



回答5:


You have to add optional binding for the above code to work. That is exclamation after UIImage as shown below.

view.backgroundColor = UIColor(patternImage: UIImage(named: "backgroundSection.png")!)




回答6:


This took me quite a bit of effort, capturing and passing along for reference. See below for full example of generation and use with swift.

Reference Example

  • GitHub(jmr): Texture Reference - '0_1_TextureRef'

Demo App

Code Excerpt

Here is how a UIView is textured in the demo, see code for full listing -

func genTexturedView(_ view:UIView) {
    ...
    image.image = UIImage(named:"purple_example");
    view.addSubview(image);

    print("ViewController.genTexturedView():    Textured View added");

    return;
}



回答7:


Swift

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



来源:https://stackoverflow.com/questions/25106784/how-to-set-a-background-image-as-colorwithpatternimage-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!