Search code examples
core-animationcalayerswift2ios9

CALayer contents not being displayed in Swift2


import UIKit

class ViewController: UIViewController {


    @IBOutlet weak var myView: UIView!



    override func viewDidLoad() {
        super.viewDidLoad()
        let url = NSURL(string: "http://blogs.independent.co.uk/wp-content/uploads/2012/12/some-girls.jpg")
        var image : UIImage? = nil
        if let data = NSData(contentsOfURL: url!) {
         image = UIImage(data: data)
        }

        let myLayer = CALayer()
        myLayer.anchorPoint = CGPoint(x: 0, y: 0)
        myLayer.bounds = CGRectMake(0, 0, self.view.bounds.width, self.view.bounds.height)
        myLayer.position = CGPoint(x: 0,y: 0)
        myLayer.borderColor = UIColor.redColor().CGColor
        myLayer.borderWidth = 2.0
      // the image is not displayed 
        myLayer.contents = image
        print(myLayer.contents)

        myView.layer.addSublayer(myLayer)
        myView.layer.opacity = 0.3
    }


}

The UIImage is not being displayed why is that? whats wrong with the code? Please Help anyone who is well versed in Core Animation and Swift


Solution

  • In CALayer CGImage is used and not UIImage Hence Convert the UIImage into CGImage like this :

    myLayer.contents = image?.CGImage
    

    This should fix that.