Similar things that don't really answer my issue
- Objective C: How to fix aspect ratio of image (and not change to fit imageview frame)
- Resize UIImage with aspect ratio?
What I am doing
User taps a 'save' button. This creates a new table view cell. Images are downloaded in another thread.
- I download an image from a URL
- Save the image
- Scale the image while keeping the aspect ratio
- Set the image to the UITableViewCell imageView that was created earlier
Problem
The problem is the last step. I want the image to fill the view and get clipped. However, the image is always drawn such that it completely fits inside the imageView with some empty white space. The images does not even fill the cell's imageView in a single dimension. It is right aligned with whitespace on the top, bottom, and left.
When I tap on the cell after the mis-drawn image is set, the cell redraws and the image is drawn to fill the imageView in one dimension but is still not clipped.
Code
I create the cell and set a temporary image
cell.imageView.image = [UIImage imageNamed:@"125-food.png"];
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
cell.imageView.layer.masksToBounds=YES;
I start the job like this:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 500000 * NSEC_PER_USEC), dispatch_get_current_queue(), ^{ /*Stuff*/ });
Scale image code
CGFloat newHeight;
CGFloat newWidth;
if(image.size.width>image.size.height)
{
newHeight = 44.0;
newWidth = image.size.width * newHeight / image.size.height;
}
else
{
newWidth = 44.0;
newHeight = image.size.height * newWidth / image.size.width;
}
CGRect newRect = CGRectMake(0,0,newWidth,newHeight);
UIGraphicsBeginImageContext(newRect.size);
[image drawInRect:newRect];
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
And then I set the newImage in the cell
cell.imageView.image = newImage;
Screen shots
The new cell does not fill the 44x44 image view, and the old cells do not get clipped.