Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Image view aspect fit with corner radius

I want to set corner radius with content mode as aspect fit using following code:

  cell.imgvAlbum.contentMode = UIViewContentModeScaleAspectFit;
  cell.imgvAlbum.clipsToBounds = YES;
  cell.imgvAlbum.layer.cornerRadius  = 5.0f;

but i am getting output only for content mode as aspect fit. I have also tried for:

  cell.imgvAlbum.layer.masksToBounds  = YES;

What to do for corner radius? Please suggest me some solution. Thanks in advance.

like image 588
Bhagyashree mahajan Avatar asked Feb 10 '23 21:02

Bhagyashree mahajan


2 Answers

Use below method to get a Rounded corner image with the specified radius for rounded corner, apply all your above properties as UIViewContentModeScaleAspectFit, clip to bounds e.t.c. on image view and set the received image by calling below function on the image view.

-(UIImage *)makeRoundedImage:(UIImage *) image
                      radius: (float) radius;
{
    CALayer *imageLayer = [CALayer layer];
    imageLayer.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    imageLayer.contents = (id) image.CGImage;

    imageLayer.masksToBounds = YES;
    imageLayer.cornerRadius = radius;

    UIGraphicsBeginImageContext(image.size);
    [imageLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return roundedImage;
}

Call as

  UIImage *image = [self makeRoundedImage:[UIImage imageNamed:@"accept~iphone"]
                    radius: 5.0f];

  cell.imgvAlbum.contentMode = UIViewContentModeScaleAspectFit;
  cell.imgvAlbum.clipsToBounds = YES;
  cell.imgvAlbum.layer.cornerRadius  = 5.0f;

  cell.imgvAlbum.layer.masksToBounds  = YES;

  [cell.imgvAlbum setImage: image];
like image 162
Sanjay Mohnani Avatar answered Feb 12 '23 11:02

Sanjay Mohnani


When using UIViewContentModeScaleAspectFit the image isn't always filling the frame of the ImageView, and that is why you could not see the corner radius.

Try putting background color to the imageView and you will see that corner radius is working.

If you want to see the round corners in any case you should use other content mode such as aspectFill or scaleToFill. example:

cell.imgvAlbum.contentMode = UIViewContentModeScaleAspectFill;

Another option would be to increase the size of the image you put in the imageView or reduce the size of the imageView.

like image 21
NIMO Avatar answered Feb 12 '23 10:02

NIMO