objective-c - 在 UITableViewCell 中的 UIImageView 上使用 cornerRadius

标签 objective-c uitableview uiimageview quartz-graphics

我为我的每个 UITableViewCells 使用一个 UIImageView 作为缩略图。我的代码使用 SDWebImage 从我的后端异步抓取这些图像并加载它们,然后缓存它们。这工作正常。

我的 UIImageView 是一个 50x50 的正方形,是在 Interface Builder 中创建的。它的背景是不透明的白色(与我的 UITableViewCell 背景颜色相同,为了性能)。但是,我想使用光滑的角以获得更好的美感。如果我这样做:

UIImageView *itemImageView = (UIImageView *)[cell viewWithTag:100];
    itemImageView.layer.cornerRadius = 2.5f;
    itemImageView.layer.masksToBounds = NO;
    itemImageView.clipsToBounds = YES;

我的表格 View 立即下降了大约 5-6 帧,在快速滚动期间达到了大约 56 FPS(这没问题),但是当我拖拉刷新控件时,它有点滞后并下降到大约 40 FPS。如果我删除 cornerRadius 行,一切都很好,没有延迟。这已使用 Instruments 在 iPod touch 5G 上进行了测试。

有没有其他方法可以让我的单元格具有圆形 UIImageView 而不会受到性能影响?我已经优化了我的 cellForRowAtIndexPath,并且在没有 cornerRadius 的情况下快速滚动时我获得了 56-59 FPS。

最佳答案

是的,那是因为 cornerRadius 和 clipToBounds 需要离屏渲染,我建议您阅读我的一篇 question 中的回答。 .我还引用了你应该看到的两个 WWDC session 。
你能做的最好的事情是在下载图像后立即抓取图像,并在另一个线程上分派(dispatch)一个对图像进行舍入的方法。最好是处理图像而不是 ImageView 。

// Get your image somehow
UIImage *image = [UIImage imageNamed:@"image.jpg"];

// Begin a new image that will be the new image with the rounded corners 
// (here with the size of an UIImageView)
 UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);

 // Add a clip before drawing anything, in the shape of an rounded rect
  [[UIBezierPath bezierPathWithRoundedRect:imageView.bounds 
                        cornerRadius:10.0] addClip];
 // Draw your image
[image drawInRect:imageView.bounds];

 // Get the image, here setting the UIImageView image
  imageView.image = UIGraphicsGetImageFromCurrentImageContext();

 // Lets forget about that we were drawing
  UIGraphicsEndImageContext();

抓取的方法here 您还可以子类化 tableviewcell 并覆盖 drawRect 方法。
肮脏但非常有效的方法是在 photoshop 中绘制一个带有内部 alpha 并围绕单元格背景匹配颜色的 mask ,并在有图像的那个上添加另一个 imageView,不透明且背景颜色清晰。

关于objective-c - 在 UITableViewCell 中的 UIImageView 上使用 cornerRadius,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17593524/

相关文章:

objective-c - UITableViews 在 Interface Builder 中使用 "Static Cells"选项布局是否可以通过代码修改?

ios - UIImageView -> UIScrollview,裁剪和裁剪 ScrollView 坐标

iphone - 如何使用 UIImageView 调整图片大小以便放大和缩小?

objective-c - 后台运行的 iOS 7 核心蓝牙外设

ios - 无需程序员干预的 Storyboard UI 更改

iphone - 网址连接 IOS 5

objective-c - DSBezelActivityView 上的内存泄漏

ios - 如何使用 NSDictionary 中的数据更改 UITableView 中单元格的文本

ios - 尝试插入第 3 节,但更新后只有 3 节

ios - 带有完成 block 的图像动画?