Med Abida Med Abida - 1 year ago 283
Swift Question

Adding image to CALayer/CAShapeLayer always shows black color

I'm trying to add an image inside a circular

so i started by creating a circle like so :

let circleContainer = UIBezierPath(arcCenter: pCenter, radius: radius - 10, startAngle: 0, endAngle: CGFloat(M_PI * 2), clockwise: true)
let imageSubLayer = CAShapeLayer()
imageSubLayer.path = circleContainer.CGPath


then to add the image i did:

let imageLayer = CALayer()
imageLayer.contents = UIImage(named: "pic")?.CGImage

//I've also tried adding the image directly to the circular CAShapeLayer like so but without any success:
imageSubLayer.contents = UIImage(named: "pic")?.CGImage

the problem is: the
is always showing black color when i run the app (see image below). what am i doing wrong ?
thanks in advance!

enter image description here

Answer Source

You've not set the frame of imageLayer. But it's also not clear what exactly you're trying to achieve. If you want your image to mask to your shape layer you'll need to set it to the mask property of imageLayer:

let imageLayer = CALayer()
imageLayer.contents = UIImage(named: "pic")?.CGImage
imageLayer.frame = view.bounds
imageLayer.mask = imageSubLayer


If you have this code in drawRect you can draw directly into the CGContext of the view. For example:

override func drawRect(rect: CGRect)
    let circleRect = CGRectInset(self.bounds, 10, 10)
    let path = UIBezierPath(ovalInRect: circleRect)
    path.lineWidth = 10
    let image = UIImage(named: "pic")

The above code draws a yellow circle with an image in the center clipped to the bounds of the circle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download