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

后端 未结 16 2504
不思量自难忘°
不思量自难忘° 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 10:47

    For those of you who don't have a subclass of UITableViewCell:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     [...]
    
          CGSize itemSize = CGSizeMake(40, 40);
          UIGraphicsBeginImageContextWithOptions(itemSize, NO, UIScreen.mainScreen.scale);
          CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
          [cell.imageView.image drawInRect:imageRect];
          cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
          UIGraphicsEndImageContext();
    
     [...]
         return cell;
    }
    

    The code above sets the size to be 40x40.

    Swift 2

        let itemSize = CGSizeMake(25, 25);
        UIGraphicsBeginImageContextWithOptions(itemSize, false, UIScreen.mainScreen().scale);
        let imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
        cell.imageView?.image!.drawInRect(imageRect)
        cell.imageView?.image! = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    

    Or you can use another(not tested) approach suggested by @Tommy:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     [...]
    
          CGSize itemSize = CGSizeMake(40, 40);
          UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0)          
     [...]
         return cell;
    }
    

    Swift 3+

    let itemSize = CGSize.init(width: 25, height: 25)
    UIGraphicsBeginImageContextWithOptions(itemSize, false, UIScreen.main.scale);
    let imageRect = CGRect.init(origin: CGPoint.zero, size: itemSize)
    cell?.imageView?.image!.draw(in: imageRect)
    cell?.imageView?.image! = UIGraphicsGetImageFromCurrentImageContext()!;
    UIGraphicsEndImageContext();
    

    The code above is the Swift 3+ version of the above.

提交回复
热议问题