Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storyboard and autolayout: how make a circular image

in storyboard (xcode 6) i want a circular user image profile take from Facebook.

So i have make this interface in storyboard, using auto layout:

enter image description here

Then, using Facebook iOS sdk i take the user profile (using swift):

 var facebookProfileUrl = "http://graph.facebook.com/\(userId!)/picture?type=normal";

In storyboard i have set the image to "Scale to fit" mode. To make the image view circular i use the following code:

self.facebookProfileImage.layer.cornerRadius =  self.facebookProfileImage.frame.size.width / 2;
self.facebookProfileImage.clipsToBounds = true;

When i run the code, anyway the image doesn't look circular:

enter image description here

I suppose the problem is auto layout but i'm not sure. How can i make the image perfectly circular??

like image 751
Tom Avatar asked Jan 27 '15 23:01

Tom


People also ask

How do I add views to my storyboard?

In storyboards, you add views by dragging them onto the view controller scene. For example, the following figure shows a view controller with an image view and button on an iPhone.

What is image view in iOS?

ImageView can be defined as an object that can display the images on the interface of the iOS applications. It is the instance of the UIImageView class, which inherits UIView.


3 Answers

Two steps:

  1. Center the UIImageView by adding a "Horizontal Center In Container" constraint (Editor > Align > Horizontal Center in Container) to the UIImageView.
  2. Remove the leading and trailing constraints you currently have set on the UIImageView.

Why? The UIImageView is getting stretched because Auto Layout needs to account for the leading and trailing constraints you set on the UIImageView. To prove my point, set the priority of the leading and trailing constraints to something less than the priority of the height and width constraints. You should see a rounded image like you expect, but it may not be centered.

like image 95
s.ka Avatar answered Oct 26 '22 09:10

s.ka


More steps:

  1. Add aspect ratio constraint 1:1
  2. mark check clip to bounds attribute in attribute inspector
  3. make outlet of your view into you controller class
  4. set corner radius to half of either its height or width

    yourImageViewOutlet.layer.cornerRadius = yourImageViewOutlet.frame.size.width / 2.0

like image 21
Y_Y Avatar answered Oct 26 '22 11:10

Y_Y


I have made the same thing a little time ago and this worked for me

self.imageView.image = [ImageHelper getImage]; //retrieve image
self.imageView.layer.cornerRadius = self.imageView.frame.size.height / 2;
self.imageView.layer.masksToBounds = YES;
self.imageView.layer.borderWidth = 0;
self.imageView.contentMode = UIViewContentModeScaleAspectFill;
like image 29
raistlin Avatar answered Oct 26 '22 10:10

raistlin