Swift2 中未显示 CALayer 内容
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
}
}
没有显示 UIImage,这是为什么?代码有什么问题?请帮助任何精通 Core Animation 和 Swift
的人
在 CALayer 中使用 CGImage 而不是 UIImage 因此将 UIImage 转换为 CGImage 如下:
myLayer.contents = image?.CGImage
这应该可以解决这个问题。
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
}
}
没有显示 UIImage,这是为什么?代码有什么问题?请帮助任何精通 Core Animation 和 Swift
的人在 CALayer 中使用 CGImage 而不是 UIImage 因此将 UIImage 转换为 CGImage 如下:
myLayer.contents = image?.CGImage
这应该可以解决这个问题。