简体   繁体   English

在tableviewcell内部调整图像大小

[英]Image resizing inside tableviewcell

I ran into a problem that can not solve 2 days. 我遇到了无法解决2天的问题。 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: 正常图片:

在此处输入图片说明

Bad image 形象不佳

在此处输入图片说明

I can not ask explicitly UIImageView because I dynamically I rely all the cells to different devices. 我不能明确地询问UIImageView,因为我动态地将所有单元格都依赖于不同的设备。

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: 内部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;
}

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. 您正在“硬编码”图像的大小,这意味着如果明年Apple推出新的iPhone,但又有不同的大小,您将遇到麻烦。 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 ). 您应该考虑使用Apple推荐的自动布局约束(这是一个很好的教程: 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. 您也可以将ImageView.contentMode设置为UIViewContentModeScaleAspectFill ,这将为您进行裁剪和调整大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM