在 UITableView 中绘制 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);
}
有解决方案吗?
So, I have a custom cell and I need to draw all images as CGImage in tableView, but I can't get it working. I have created a test project and tested the code with simple views. Everything worked perfect, and when I copypasted the same code to my custom cell it stopped working. Here is the code:
-(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);
}
Any solutions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Apple 建议将自定义视图添加到 UITableViewCell 的 contentView,而不是更改 UITableViewCell 本身。请参阅 TimeZoneCell 对于 例子。
Apple recommends to add your custom view to the UITableViewCell's contentView instead of changing UITableViewCell itself. See TimeZoneCell for an example.
在你的drawRect方法中,你可能应该调用[super drawRect:rect];
In your drawRect method, you should probably call [super drawRect:rect];
好的,问题是具有自定义背景颜色的单元格的 contentView 隐藏了图像。这是正确的代码:
OK, the problem was that contentView of the cell with custom background color was hiding the image. Here is the right code: