[英]Round UIImages in UITableView causes slowdown
當我嘗試對所有自定義UITableViewCells中的UIImage進行四舍五入時,UITableView的滾動會明顯變慢且不穩定。 有什么更好的辦法嗎?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.profileLabel.text = [[demoArray objectAtIndex:[indexPath row]] objectForKey:@"name"];
cell.imageView.image = [UIImage imageNamed:[[demoArray objectAtIndex:[indexPath row]] objectForKey:@"image"]];
cell.imageView.layer.cornerRadius = 9.0;
cell.imageView.layer.masksToBounds = YES;
return cell;
}
雖然調整圖層的拐角半徑當然很方便,但可能會降低性能。 我個人將以這種非常簡單的方式進行操作。
在任何圖形編輯器中創建一個疊加層-使用與單元格背景相同的顏色填充角落,使它們與所需形狀匹配。 現在,將新的UIImageView
添加到您的單元格中,將其直接放置在圖像上方,並確保疊加層位於頂部。
1)您可以在viewDidLoad中創建舍入的圖像(或在數據准備就緒時)並將其保存到臨時數組中。 為此,您只需像現在一樣創建它即可。 然后,您將視圖內容捕獲到新圖像中。 然后,您可以在表格視圖中顯示新創建的圖像,而無需動態遮罩。
要將viewcontents保存到圖像中,可以使用以下代碼:
- (UIImage*) screenshotOfView: (UIView*) view
{
UIGraphicsBeginImageContext(view.frame.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return viewImage;
}
好吧,我會更具體。 目前,您的demoArray
充滿了數據。 您遍歷該數組並預渲染圖像。 那就是您的操作方式(使用上述方法):
for(NSDictionary* dictionary in demoArray)
{
UIImage* originalImage = [UIImage imageNamed:[dictionary objectForKey:@"image"]];
UIImageView* tmpImageView = [[UIImageView alloc] initWithImage: originalImage];
tmpImageView.layer.cornerRadius = 9.0;
tmpImageView.layer.masksToBounds = YES;
UIImage* roundedImage = [self screenshotOfView: tmpImageView];
[dictionary setObject: roundedImage forKey: @"roundedImage"];
}
然后在cellForTableRow
方法中,只需使用該圖像:
cell.imageView.image = [UIImage imageNamed:[[demoArray objectAtIndex:[indexPath row]] objectForKey:@"roundedImage"]];
(此代碼未經測試,只是寫下來了……)
2)另一個可能更快的解決方案是在drawRect:
通過CoreGraphics掩蓋)內的tableViewCell子類中繪制圖像,但這更加復雜。
3)按照Bartosz Ciechanowski的回答,您可以使用CorGraphics為每種尺寸動態創建所需的overlayImage。 但是第一個解決方案可能是最簡單的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.