2

I use this category and create images for my UITableView to all be the same size. Is there a way to have the images have rounded corners as well? Thanks!

+ (UIImage *)scale:(UIImage *)image toSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

Edit: I then get the image, and other object info to put it in an NSDictionary to get in the UITableView. I tried changing the UIImageView.layer property in the cellForRowAtIndexPath, but it doesn't seem to do the trick:

cell.TitleLabel.text = [dict objectForKey:@"Name"];
cell.CardImage.image = [dict objectForKey:@"Image"];
cell.CardImage.layer.cornerRadius = 5.0;
JOM
  • 8,139
  • 6
  • 78
  • 111
Crystal
  • 28,460
  • 62
  • 219
  • 393

4 Answers4

7

You can add clipping to the drawing operation, the UIBezierPath class makes this super easy.

Extend you code to:

+ (UIImage *)scale:(UIImage *)image toSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    [[UIBezierPath bezierPathWithRoundeRect:rect cornerRadius:5] addClip];
    [image drawInRect:rect];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
PeyloW
  • 36,742
  • 12
  • 80
  • 99
  • 1
    fyi there's a missing 'd' in bezierPathWithRoundedRect:rect. I'd just edit the answer but there's a minimum 6 character change to edit something. Just thought I'd point out in case someone else spends time trying to figure out why there's no known method "bezierPathWithRoundeRect:rect" and missed the typo :) very nice answer though – Eric D'Souza Apr 08 '13 at 22:15
  • This approach can lead to blurry corners on retina devices. This works very well: http://stackoverflow.com/a/4334902/1022589 – That Guy Feb 06 '15 at 10:42
1

Try this

image.layer.cornerRadius = 5;
Sisu
  • 716
  • 3
  • 6
1
  1. Include QuartzCore framework.
  2. Import CALayer.h
  3. image.layer.cornerFRadius = 5;
the.evangelist
  • 488
  • 5
  • 18
0

As said Sisu and the.evangelist : image.layer.cornerRadius = 5;

But you may need to also add :

[image.layer setMasksToBounds:YES];