3

I'm using a grouped tableview with some custom cells, and an image as each cell's backgroundColor.

cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"custombackground.png"]];

So far, all is good, but my image is significantly taller than the height of a regular cell, and therefore, only the top part of the image is being used as the background, and each cell is identical. Basically, it looks sloppy with each cell repeating the pattern.

Has anyone done this so the second row of the section displays the next part of the image instead of repeating it, so it looks like a single continuous image? (e.g. row 0 uses the first 44 pts of the image, row 1 uses pts 45-88, etc.)

Is it possible, and/or any ideas how to?

gyratory circus
  • 437
  • 6
  • 15

2 Answers2

1

Yes, you can do this. The key to this problem is using UIImage's CGImage method, and then using Quartz "CGImageRef CGImageCreateWithImageInRect();" to create sub images. With a CGImageRef you can create new UIImages.

So lets say its just the height that is the problem. The first cell uses a partial image from the top down "h" pixels. Then the next starts at "h" and goes another h pixels, etc.

Note that Quartz uses a "flipped" coordinate system, so you will have to fiddle with exactly where you grab the sub image from. When I do this I always seem to need some tweaking, so expect to spend a bit of time at the end getting it to show properly.

David H
  • 40,852
  • 12
  • 92
  • 138
0

You can calculate each row's portion size by indexPath.row variable. After that, crop your image with CGRect values you calculated.

CGFloat top = (indexPath.row == 0) ? 0 : (indexPath.row * 44) + 1;

CGRectMake(0, top, 320, 44); is your rect for cropping image

You can use this answers for cropping an UIImage.

OP EDIT: Thanks! Adding what I came up with from the suggestions:

    UIImage *image = [UIImage imageNamed:@"custombackground.png"];
    CGFloat y = indexPath.row * 44;

    for (y; y+44 > image.size.height; y -= image.size.height);
    //Sends our y origin back to the top of the image in case
    //the image would have ended in the middle of a cell, so 
    //it can be used for any length of table.

    CGRect cropRect = CGRectMake(0, y, 320, 44);
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);

    cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithCGImage:imageRef]];
Community
  • 1
  • 1
Samet DEDE
  • 1,621
  • 19
  • 28