Rounded Rect's in custom cell, UITableViewController while maintaining aspect ratio

198 views Asked by At

While referencing UIImage with rounded corners I'm able to create images that have rounded rects. This has definitely helped my scroll refresh rates.

The problem I now have is that I generally use UIViewContentModeScaleAspectFill while drawing my UIImages into view's.

Drawing with a UIBezierPath and then putting the image in its bounds is making the image loose its aspect ratio.

[UIBezierPath bezierPathWithRoundedRect:imageView.bounds 
                    cornerRadius:10.0] addClip];

[image drawInRect:imageView.bounds];

Is the only way out by writing a custom scale solution?

Thanks

3

There are 3 answers

0
tassar On BEST ANSWER
GSize size1 = image.size;
CGSize size2 = imageView.bounds.size;
CGRect newRect;
if (size1.width / size1.height > size2.width / size2.height) {
    CGFloat newWidth = size2.height * size1.width / size1.height;
    newRect = CGRectMake((size2.width - newWidth)/2, 0, newWidth, size2.height);
} else {
    CGFloat newHeight = size1.height / size1.width * size2.width;
    newRect = CGRectMake(0, (size2.height - newHeight)/2, size2.width, newHeight);
}
[image drawInRect:newRect];
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
0
rdelmar On

The problem is that the method you reference uses the image view's bounds as the size of the image context, and it might not have the right aspect ratio, so you need to set the size of the image view first, before passing it in. So, if you want all the image views to have the same width, pass in that width, and a height that's determined from that width and the aspect ratio of the image.

CGFloat height = imageView.bounds.size.width * (image.size.width/image.size.height);

0
Krumelur On

I would recommend you look at using layer compositing if possible, instead of trying to draw the whole thing yourself. For example:

  • Create a CALayer with a roundrect content
  • Use a standard way of presenting the image (i.e. UIImageView)
  • Set the mask property of the image layer to the roundrect layer

See this article or this question for some ideas.