user2759544
user2759544

Reputation: 181

Image resizing inside tableviewcell

I ran into a problem that can not solve 2 days. On the server image and come before inserting them in the box, I cut them on the client to fit the screen. Everything is good but the images change randomly height. Now the height is calculated independently - in proportion to the width. Normal image:

enter image description here

Bad image

enter image description here

I can not ask explicitly UIImageView because I dynamically I rely all the cells to different devices.

My resize function:

-(UIImage *)resizeImage :(UIImage *)theImage :(CGSize)theNewSize {
UIGraphicsBeginImageContextWithOptions(theNewSize, NO, 1.0);
CGFloat height = theImage.size.height;
CGFloat newHeight = 0;
newHeight = (theNewSize.width * height) / theImage.size.width;
newHeight = floorf(newHeight);
NSLog(@"new height image %f", newHeight);
[theImage drawInRect:CGRectMake(0, 0, theNewSize.width, newHeight)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}

inside layoutSubviews:

if(device == thisDeviceClass_iPhone5) {
    [self.imageView setFrame:CGRectMake(0,0, 320, 255)]; //180
    offset = 0;
    padding = 5;
} else if(device == thisDeviceClass_iPhone6){
    [self.imageView setFrame:CGRectMake(0,0, 375, 255)]; //211
    offset = 25;
} else if(device == thisDeviceClass_iPhone6plus) {
    [self.imageView setFrame:CGRectMake(0,0, 414, 255)]; //233
    offset = 40;
}

Upvotes: 0

Views: 53

Answers (1)

null
null

Reputation: 1178

Your approach is very old school. You are "hard coding" the size of the image which means that if next year Apple came up with a new iPhone that have, yet again, a different size you'll be in trouble. You should consider using auto-layout constrains which is Apple's recommended approach (here is a good tutorial: http://www.raywenderlich.com/50317/beginning-auto-layout-tutorial-in-ios-7-part-1).

You can also set the ImageView.contentMode to UIViewContentModeScaleAspectFill which will do the crop and resize for you.

Upvotes: 1

Related Questions