我想为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;
}
答案 0 :(得分:3)
首先是第一件事:您不需要推送图形上下文。摆脱UIGraphicsPushContext
和UIGraphicsPopContext
行。
其次,如何画出你想要的东西:
-(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;
}