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

Первое, что необходимо сделать: вам не нужно толкать графический контекст. Избавьтесь от линий 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; 
} 
+0

Cut, Paste и работает (когда я установил правописание цвета :)) Высокий, спасибо – Xetius