views:

85

answers:

1

I want to dynamically create an image for a UITableViewCell which is basically a square with a number in it. The square has to be a colour (specified dynamically) and contains a number as text inside it.

I have looked at the CGContextRef documentation, but can't seem to work out how to get the image to fill with a specified certain colour.

This is what I have been trying so far.

-(UIImage*)createCellImageWithCount:(NSInteger)cellCount AndColour:(UIColor*)cellColour {

    CGFloat height = IMAGE_HEIGHT;
    CGFloat width = IMAGE_WIDTH;
    UIImage* inputImage;

    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIGraphicsPushContext(context);

    // drawing code goes here
        // But I have no idea what.

    UIGraphicsPopContext();
    UIImage* outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return outImage;
}
+2  A: 

First thing's first: You don't need to push the graphics context. Get rid of the UIGraphicsPushContext and UIGraphicsPopContext lines.

Second, how to draw what you want:

-(UIImage*)createCellImageWithCount:(NSInteger)cellCount AndColour:(UIColor*)cellColour {

    CGFloat height = IMAGE_HEIGHT;
    CGFloat width = IMAGE_WIDTH;
    UIImage* inputImage;

    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    CGContextRef context = UIGraphicsGetCurrentContext();

    [cellColour set];  // Set foreground and background color to your chosen color
    CGContextFillRect(context,CGRectMake(0,0,width,height));  // Fill in the background
    NSString* number = [NSString stringWithFormat:@"%i",cellCount];  // Turn the number into a string
    UIFont* font = [UIFont systemFontOfSize:12];  // Get a font to draw with.  Change 12 to whatever font size you want to use.
    CGSize size = [number sizeWithFont:font];  // Determine the size of the string you are about to draw
    CGFloat x = (width - size.width)/2;  // Center the string
    CGFloat y = (height - size.height)/2;
    [[UIColor blackColor] set];  // Set the color of the string drawing function
    [number drawAtPoint:CGPointMake(x,y) withFont:font];  // Draw the string

    UIImage* outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return outImage;
}
Ed Marty
Cut, Paste and works (When I fixed the spelling of Colour :) ) Awesome, thanks
Xetius