Search code examples
swiftswift3uiimageviewuiimagecashapelayer

Insert CAShapeLayer behind Image in UIImageView


Just as the title says. I have a UIImageView and I am inserting CAShapeLayers into the View. The issue is that I don't know how to insert them behind the image of the UIImageView. Any advice would be much appreciated, thanks.


Solution

  • You could try to do some layer re-ordering, but you might be foiled by UIImageView's own internal code. My suggestion would be be to create a container view and add your sublayers there, then add the image view as a subview (which is essentially adding it as a sublayer as well). As long as the image has transparency and the UIImageView is not opaque, it will work. This code worked for me in a playground:

    let container = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    let imageView = UIImageView(frame: container.bounds)
    imageView.image = UIImage(named: "duck.png")
    imageView.isOpaque = false
    
    let shape = CAShapeLayer()
    shape.path = UIBezierPath(roundedRect: container.bounds, cornerRadius: 2).cgPath
    shape.strokeColor = UIColor.black.cgColor
    shape.lineWidth = 10
    shape.fillColor = UIColor.blue.cgColor
    shape.borderColor = UIColor.black.cgColor
    container.layer.addSublayer(shape)
    container.addSubview(imageView)
    

    Good luck!