我创建了一个在角落显示页码的文档 View 。页码是一个带有半透明背景色的 uilabel,并且有一个圆角半径(使用 view
的 layer
的 cornerRadius
属性>).我已将其置于 UIScrollView
之上。但是,这会使滚动变得不稳定。如果我删除 cornerRadius
,性能会很好。我能做些什么吗?什么是更好的解决方案?它似乎是在 UIWebView
中实现的,没有任何性能问题。
最佳答案
对于带有圆角和/或 ScrollView 上的背景颜色和阴影的标签或 View ,解决方案非常简单:
最大的问题来自 masksToBounds 图层选项。这似乎会显着降低性能,但标签似乎需要此 ON 才能将背景颜色遮盖到圆角。因此,要解决此问题,您需要改为设置标签层背景颜色并关闭 masksToBounds。
第二个问题是默认行为是尽可能重绘 View ,这对于 ScrollView 上的静态或缓慢变化的项目来说是完全不必要的。这里我们简单设置layer.shouldRasterize = YES。这将允许 CA 在滚动时“缓存” View 的光栅化版本以便快速绘制(可能具有硬件加速)。
您需要确保您的图层具有 Alpha channel ,否则栅格化会影响圆角的绘制。我从来没有遇到过问题,因为我为我的背景颜色设置了 alpha,但你可能需要检查你的情况。
这里是一个 UILabel 示例,设置为在 scollview 上很好地工作:
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(4, 4, 40.0, 24.0)];
lbl.font = [UIFont fontWithName:@"Helvetica" size:14.0];
lbl.textAlignment = UITextAlignmentRight;
lbl.text = @"Hello World";
// Must set the label background to clear so the layer background shows
lbl.backgroundColor = [UIColor clearColor];
// Set UILabel.layer.backgroundColor not UILabel.backgroundColor otherwise the background is not masked to the rounded border.
lbl.layer.backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.5].CGColor;
lbl.layer.cornerRadius = 8;
lbl.layer.borderColor = [UIColor blackColor].CGColor;
lbl.layer.borderWidth = 1;
// Huge change in performance by explicitly setting the below (even though default is supposedly NO)
lbl.layer.masksToBounds = NO;
// Performance improvement here depends on the size of your view
lbl.layer.shouldRasterize = YES;
lbl.layer.rasterizationScale = [UIScreen mainScreen].scale;
// self here is the child view in the scroll view
[self addSubview:lbl];
[lbl release];
我可以用这样的 View 填满 iPad 1 屏幕,并且仍然可以平滑滚动 :)
关于ios - UILabel 层 cornerRadius 对性能产生负面影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4735623/