2010-05-27 62 views
0

我想动态地为UITableViewCell创建图像,该图像基本上是一个带有数字的正方形。正方形必须是一种颜色(动态指定),并在其中包含一个数字作为文本。如何为UITableViewCell动态创建图像

我已经看过CGContextRef文档,但似乎无法弄清楚如何让图像填充指定的某种颜色。

这是我一直在尝试的东西。

-(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; 
} 

回答

3

第一件事情的第一件事:您不需要推送图形上下文。摆脱UIGraphicsPushContextUIGraphicsPopContext行。

二,如何吸引你想要什么:

-(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; 
} 
+0

剪切,粘贴和工作(当我固定颜色的:)拼写)真棒,谢谢 – Xetius 2010-05-28 17:16:50