当我使用imageView.layer.shouldRasterize = YES

时间:2016-08-31 09:24:04

标签: ios objective-c uitableview core-graphics

我的应用程序有一个UITableView和包含几个UIImageViews的单元格,这些imageViews有一层阴影和cornerRadius。 为了提高性能,我使用

//if set to NO, tableView is slow to move
imageView.layer.shouldRasterize = YES;

//solve image become blurry problem
imageView.layer.rasterizationScale = [[UIScreen mainScreen] scale];

但是当我加载许多单元格时,它会使用大量内存并因此错误而崩溃:

  

CGBitmapContextInfoCreate:无法为位图数据分配283136个字节

我该如何解决这个问题?

修改1

在CAlayer.h中

/* When true, the layer is rendered as a bitmap in its local coordinate
* space ("rasterized"), then the bitmap is composited into the
* destination (with the minificationFilter and magnificationFilter
* properties of the layer applied if the bitmap needs scaling).
* Rasterization occurs after the layer's filters and shadow effects
* are applied, but before the opacity modulation. As an implementation
* detail the rendering engine may attempt to cache and reuse the
* bitmap from one frame to the next. (Whether it does or not will have
* no affect on the rendered output.)
*
* When false the layer is composited directly into the destination
* whenever possible (however, certain features of the compositing
* model may force rasterization, e.g. adding filters).
*
* Defaults to NO. Animatable. */

@property BOOL shouldRasterize;

'尝试缓存'

我认为它会将图像和这些阴影数据加载到内存中并导致它占用大量内存。

Performance scrolling and retina resolution images in CALayer

Drawing mask influence performance

完整代码:

imageView.layer.borderWidth = 0.2;
imageView.layer.borderColor = [UIColor colorWithWhite:0.95 alpha:1].CGColor;
imageView.layer.cornerRadius = 2;

imageView.layer.shouldRasterize = YES;
imageView.layer.rasterizationScale = [[UIScreen mainScreen] scale];


UIView *shadowView = [[UIView alloc] init];
shadowView.backgroundColor = [UIColor whiteColor];

//set layer, if I don't use shadow view
shadowView.layer.shadowColor = [UIColor colorWithWhite:0.93 alpha:1].CGColor;
shadowView.layer.cornerRadius = 2;
shadowView.layer.shadowOffset = CGSizeMake(1,1);
shadowView.layer.shadowOpacity = 1;
shadowView.layer.shadowRadius = 0.6;
shadowView.layer.shouldRasterize = YES;
shadowView.layer.rasterizationScale = [[UIScreen mainScreen] scale];
[shadowView setFrame:containerFrame];

[shadowView addSubview:imageView];

//add shadowView to cell ...

1 个答案:

答案 0 :(得分:0)

尝试在imageView下添加视图仅用于阴影并使用相同的设置,但不能用于imageView。

确保 shadowView.layer.shouldRasterize = YES; shadowView.layer.rasterizationScale = [[UIScreen mainScreen] scale]; 在单元初始化时调用一次