在UITableView中绘制CGImage

时间:2011-09-01 22:24:16

标签: iphone core-graphics cgimage

所以,我有一个自定义单元格,我需要在tableView中将所有图像绘制为CGImage,但我无法使其正常工作。我创建了一个测试项目,并使用简单的视图测试了代码。一切都很完美,当我将相同的代码复制到我的自定义单元格时,它就停止了工作。这是代码:

-(void)drawRect:(CGRect)rect {
    CGRect contentRect = self.contentView.bounds;
    CGFloat boundsX = contentRect.origin.x;

    UIImage *karmaImage = [UIImage imageNamed:@"karma.png"];
    [self drawImage:karmaImage withRect:CGRectMake(boundsX + 255, 16, 14, 14)];
}
-(void)drawImage:(UIImage *)image withRect:(CGRect)rect {
    CGImageRef imageRef = CGImageRetain(image.CGImage);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextDrawImage(context, rect, imageRef);
}

任何解决方案?

3 个答案:

答案 0 :(得分:3)

Apple建议将自定义视图添加到UITableViewCell的contentView,而不是更改UITableViewCell本身。有关示例,请参阅TimeZoneCell

答案 1 :(得分:0)

在drawRect方法中,您应该调用[super drawRect:rect];

答案 2 :(得分:0)

好的,问题是具有自定义背景颜色的单元格的contentView正在隐藏图像。这是正确的代码:

-(void) drawRect:(CGRect)rect{
    [super drawRect:rect];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor colorWithRed:(232.0/255.0) green:(232.0/255.0) blue:(232.0/255.0) alpha:1.0].CGColor);
    CGContextFillRect(context, rect);
    UIImage *karmaImg = [UIImage imageNamed:@"karma.png"]; 
    [self drawImage:karmaImg withContext:context atPoint:CGPointMake(boundsX + 255, 16)];
}


-(void)drawImage:(UIImage *)image withContext:(CGContextRef)context atPoint:(CGPoint)point {
    if(image) {
        CGContextDrawImage(context, CGRectMake(point.x, point.y, image.size.width, image.size.height), image.CGImage);
    } else {
        NSLog(@"Error: Image failed to load.");
    }
}