0

The code below prints a line on a UIView. I just want to know the code that I would write to be able to insert an image on top of the view. Many people will point to this question but it does not work. I have tried it several times. The code I tried below is having no effect.

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)
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579

2 Answers2

2

First you create a UIImage from your image file, then create a UIImageView from that:

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)

  }

}
B K.
  • 534
  • 5
  • 18
  • This is not working. I have attached my code via dropbox link dropbox.com/s/ksnshbj40vn78qf/draw.zip?dl=0. Can you look at it? –  May 09 '19 at 03:14
0

You need to add canVasView as Subview to UIViewController view and add the image in assets. 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)
    }
}
Ben Rockey
  • 920
  • 6
  • 23
  • This is not working. I have attached my code via dropbox link https://www.dropbox.com/s/ksnshbj40vn78qf/draw.zip?dl=0. Can you look at it? –  May 09 '19 at 03:13
  • sorry for the delay. add image in assets rather than adding direct. See the updated answer. – Ben Rockey May 16 '19 at 05:32