如何在uiview上插入图片

时间:2019-04-30 03:09:15

标签: ios swift uiview layer subview

下面的代码在UIView上打印一行。我只想知道我编写的能够在视图顶部插入图像的代码。很多人会point to this question,但是它不起作用。我已经尝试了几次。我在下面尝试的代码无效。

class ViewController: UIViewController {
    var canVasView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        let myLayer = CALayer()
        let myImage = UIImage(named: "star")?.cgImage
        myLayer.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
        myLayer.contents = myImage
        canVasView.layer.addSublayer(myLayer)
    }
}

2 个答案:

答案 0 :(得分:1)

首先,您从图像文件中创建一个UIImage,然后从该文件中创建一个UIImageView

class ViewController: UIViewController {
  //  var canVasView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

    let imageName = "star.png"
    let image = UIImage(named: imageName)
    let imageView = UIImageView(image: image!)

   // Finally you'll need to give `imageView` a frame and add it your view for it to be visible:

    imageView.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
   // canVasView.addSubView(imageView)
    self.view.bringSubviewToFront(imageView)

  }

}

答案 1 :(得分:0)

您需要将canVasView作为子视图添加到UIViewController视图,并将图像添加到资产中。 See Image

class ViewController: UIViewController {

    var canVasView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        let myLayer = CALayer()
        let myImage = UIImage(named: "graph")?.cgImage
        myLayer.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
        myLayer.contents = myImage
        canVasView.layer.addSublayer(myLayer)

        self.view.addSubview(canVasView)
    }
}