Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize image to fit UITableView cell?

How to fit UIImage into the cell of UITableView, UITableViewCell (?).

Do you addSubview to cell or is there a way to resize cell.image or the UIImage before it is assigned to cell.image ?

I want to keep the cell size default (whatever it is when you init with zero rectangle) and would like to add icon like pictures to each entry. Images are slightly bigger than the cell size (table row size).

I think the code looks like this (from top of my head):

UIImage * image = [[UIImage alloc] imageWithName:@"bart.jpg"];
cell = ... dequeue cell in UITableView data source (UITableViewController ...)
cell.text = @"bart";
cell.image = image;

What do I need to do to resize the image to fit the cell size? I've seen something like:

UIImageView * iview = [[UIImageView alloc] initWithImage:image];
iview.frame = CGRectMake(...); // or something similar
[cell.contentView addSubview:iview]

The above will add image to cell and I can calculate the size to fit it, however:

  1. I'm not sure if there is a better way, isn't it too much overhead to add UIImageView just to resize the cell.image ?
  2. Now my label (cell.text) needs to be moved as it is obscured by image, I've seen a solution where you just add the text as a label:

Example:

UILabel * text = [[UILable alloc] init];
text.text = @"bart";
[cell.contentView addSubview:iview];
[cell.contentView addSubview:label];
// not sure if this will position the text next to the label
// edited original example had [cell addSubview:label], maybe that's the problem

Could someone point me in correct direction?

EDIT: Doh [cell.contentview addSubview:view] not [cell addSubview:view] maybe I'm supposed to look at this:

- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = ...;
    CGRect frame = cell.contentView.bounds;
    UILabel *myLabel = [[UILabel alloc] initWithFrame:frame];
    myLabel.text = ...;
    [cell.contentView addSubview:myLabel];
    [myLabel release];
}
like image 938
stefanB Avatar asked May 18 '09 23:05

stefanB


2 Answers

This site posts code on rescaling a UIImage*. You could play with the scaling to get the right ratio for the UIImage* you are using, to scale it down.

like image 64
Alex Reynolds Avatar answered Nov 08 '22 11:11

Alex Reynolds


If you have access to the apple devloper center, there is a video about scaling images for table views. It is more focused on performance issues and talks lots about threading, but he does shows some sample code used to resize images.

Video name: "Effective iPhone App Development - Part 2" about 30 mins in.

like image 1
Robert Avatar answered Nov 08 '22 11:11

Robert