2011-09-01 26 views
1

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

Apple建议将自定义视图添加到UITableViewCell的contentView,而不是更改UITableViewCell本身。一个例子见TimeZoneCell

+0

+1你不应该试图来覆盖'UITableViewCell'本身的图纸。你会打破各种事情。 –

0

在你的drawRect方法中,你可能应该调用[super drawRect:rect];

+0

一切都没变...... –

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."); 
    } 
} 
+0

我很好奇;为什么不在创建单元格时将图像绘制到uiImageView上(或者对于所有单元格甚至只绘制一次),并将其添加到contentView中,而不是每次出现单元格时重新加载/绘制图像。这看起来更干净更快。 – mackworth