0

我想为 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;
}
4

1 回答 1

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;
}
于 2010-05-27T22:09:01.407 回答