2010-05-27 88 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