Why does adding an align with centre constraint to

2019-09-06 14:15发布

问题:

I am trying to turn a square image into a circle. I am using this code to do it:

 profilePicture2.layer.cornerRadius = profilePicture2.frame.size.height/2   
 profilePicture2.clipsToBounds = true

It works perfectly, until I try centre the image in the container view by adding a 'Align centre X to superview' constraint. When I add this constraint I simply get very rounded corners instead of a circle.

In fact, it seems to half the value of the corner radius. So if the image has a height of 100, and corner radius should be set to 50, it LOOKS like the radius value is set to 25.

No other constraints have been added to the image.

What is going on here?

回答1:

You are calling this code (profilePicture2.layer.cornerRadius = profilePicture2.frame.size.height/2) before the image is being resized. You need to do it after the autolayout has finished work. The problem is that the image at the start is (for example) 100 points wide and you set the corner radius to 50 points. And after that autolayout resizes the image to (again, example) 300 points but your corner radius remains 50 points. You just need to update it after autolayout has completed.

Or if you do not want to have an image that big, make sure you put constraints on width and height and just center it the superview.