How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

后端 未结 16 2535
不思量自难忘°
不思量自难忘° 2020-11-27 10:27

I have a bunch of images I am using for cell\'s image views, they are all no bigger than 50x50. e.g. 40x50, 50x32, 20x37 .....

When I load the table view, the tex

16条回答
  •  伪装坚强ぢ
    2020-11-27 11:07

    This solution essentially draws the image as 'aspect fit' within the given rect.

    CGSize itemSize = CGSizeMake(80, 80);
    UIGraphicsBeginImageContextWithOptions(itemSize, NO, UIScreen.mainScreen.scale);
    UIImage *image = cell.imageView.image;
    
    CGRect imageRect;
    if(image.size.height > image.size.width) {
        CGFloat width = itemSize.height * image.size.width / image.size.height;
        imageRect = CGRectMake((itemSize.width - width) / 2, 0, width, itemSize.height);
    } else {
        CGFloat height = itemSize.width * image.size.height / image.size.width;
        imageRect = CGRectMake(0, (itemSize.height - height) / 2, itemSize.width, height);
    }
    
    [cell.imageView.image drawInRect:imageRect];
    cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

提交回复
热议问题