代码之家  ›  专栏  ›  技术社区  ›  Xetius

如何为UITableViewCell动态创建图像

  •  0
  • Xetius  · 技术社区  · 15 年前

    我想动态地为一个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;
    }
    
    1 回复  |  直到 15 年前
        1
  •  3
  •   Xetius    15 年前

    第一件事是:你不需要推动图形环境。摆脱 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;
    }