Jassi
Jassi

Reputation: 557

How to round an image automatically in Portrait and Landscape?

I have a UIImageView of 100*100 which I am rounding in a circle shape using below code:

imageView.layer.cornerRadius = imageView.frame.size.width/2

There is a constraint added to this imageView with aspect ratio to superview. This is because I need to change the imageView size accordingly as the superview size changes.

Problem: When I rotate the view in landscape mode, the imageView is resized but it doesn't gets rounded. I have added screenshots for it.

How/Where should I make it rounded again. Should I register to a notification and then set the rounding again. As the imageView size has changed. Is there anything that auto-layout could manage itself.

Please give a good solution.

In portriat mode In Landscape mode

Edit:

Here is the imageView Constraint

enter image description here

Upvotes: 1

Views: 513

Answers (3)

Bannings
Bannings

Reputation: 10479

You can update the cornerRadius of the imageView in didRotateFromInterfaceOrientation method:

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    imageView.layer.cornerRadius = imageView.bounds.size.width / 2;
}

This will be called only when the screen rotated to a new orientation if the view controller supports the new orientation.


Or update its cornerRadius in viewDidLayoutSubviews:

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    imageView.layer.cornerRadius = imageView.bounds.size.width / 2;
}

You should regardless of how many times the method executed. It will always keep the correct result at the time.

Upvotes: 2

Alaeddine
Alaeddine

Reputation: 6212

Try this In you ViewController

 - (void)layoutSubviews
 {
    [super layoutSubviews];

    NSLog(@"%f", imageView.frame.size.width/2);

    layer.cornerRadius = imageView.frame.size.width/2;
 }

Upvotes: 0

Kishore Suthar
Kishore Suthar

Reputation: 2983

Use this when landscape mode

[imageView layoutIfNeeded];

then

imageView.layer.cornerRadius = imageView.frame.size.width/2

Upvotes: 0

Related Questions