2

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.

Blue
  • 1,408
  • 4
  • 17
  • 36
  • Don't mess with the UIImageView's layer. Follow @LeoDabus suggestion and wrap it over a UIView and add the layer to the later – hfehrmann Sep 12 '17 at 21:28
  • Neither of you answered my question. I am aware that I could create a second view underneath/as a container but for many reasons I'd like to avoid such a solution. Also I have inserted the layers into the UIImageView and everything is working well and testing well. The only issue is that I don't know how to insert things below the image. If this is not possible then say "That is not possible", if you are not sure then you shouldn't be answering. But please don't waste my time, I asked the specific question I did for a reason. – Blue Sep 12 '17 at 21:38
  • @LeoDabus So you don't know the answer? Thanks for trying, have a great day. – Blue Sep 12 '17 at 21:53
  • @LeoDabus I didn't know hence why I asked. Also I don't think bragging about answered questions is very appropriate for a site like stackoverflow especially if you are as involved as you say you are, this isn't reddit. – Blue Sep 12 '17 at 21:59
  • Go through https://stackoverflow.com/a/61703220/10505343 answer. It will help you to solve this question. – Wimukthi Rajapaksha May 09 '20 at 20:30

1 Answers1

5

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!

swift taylor
  • 610
  • 5
  • 10
  • 3
    So what you're saying is that the UIImageView might not allow for anything to exist below the image and I have to make a separate view container. That's too bad. Thanks for taking the time tho. – Blue Sep 12 '17 at 21:56