Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sublayer is not showing up after add it

I'm trying to add the image "resizeLayer" over my UIView selectedShape by sublayering it over selectedShape

let sublayer = CALayer()
sublayer.bounds = selectedShape.bounds //even when inserted this line, sublayer still doesn't show up
sublayer.frame = selectedShape.frame
sublayer.contents = UIImage(named: "resizeLayer")
selectedShape?.layer.addSublayer(sublayer)

But when I run my code I don't see the layer at all

I even tried subviewing the image "resizeLayer" over the UIView "selectedShape"

let resizeFrame = UIImageView(image: UIImage(named: "resizeLayer"))
resizeFrame.frame = selectedShape.frame
resizeFrame.contentMode = UIViewContentMode.ScaleAspectFill
selectedShape.addSubview(resizeFrame)

But still, the "resizeLayer" does not show up!

It only shows up if I add the "resizeLayer" to the overall view:

let resizeFrame = UIImageView(image: UIImage(named: "resizeLayer"))
resizeFrame.frame = selectedShape.frame
resizeFrame.contentMode = UIViewContentMode.ScaleAspectFill
selectedShape.addSubview(resizeFrame)     
self.view.insertSubview(resizeFrame, aboveSubview: selectedShape) //add this line

Any help on this would be really appreciated!

If it's relevant, this is how I made selectedShape

selectedShape = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 60))
selectedShape.layer.cornerRadius = 10
selectedShape.backgroundColor = UIColor.blueColor()
canvas.addSubview(selectedShape) //canvas is the view I'm adding selectedShape to

This is the image "resizeLayer" that I'm trying to add

The blue square is selectedShape. As you can see the layer is not showing up.

What I want to happen

like image 971
14wml Avatar asked Dec 15 '22 09:12

14wml


2 Answers

You are using the entire frame for selectedShape. You should only use the width and the height because x and y should be zero. The image is added to selectedShape so the point (0,0) is the top left of the selectedShape view.

resizeFrame.frame = CGRect(origin: CGPointZero, size: selectedShape.frame.size)

I will admit that this stumped me for longer than it should have.

like image 165
Caleb Avatar answered Dec 23 '22 07:12

Caleb


Not really an answer to his problem, but related and would have saved me time if somone had written this here before. So in hope to help someone and compile a more complete list of problems and their solution:

The addSublayer call needs to be made from the main-thread...

The funny thing is if you do it from a worker-thread it still shows up in the view-hirarchy-debugging with the content you set, but it's not displayed...

like image 22
moritz Avatar answered Dec 23 '22 07:12

moritz