阴影减慢 UIScrollView

Shadows slow up UIScrollView

我有一个 UIScrollView 功能与 Facebook news feed 非常相似。我认为我的元素正在减慢滚动 fps。通过消除过程,我发现 shadows 减慢了我的应用程序

滚动视图中的UIView个框有这样的配置:

self.layer.shadowColor = UIColor.blackColor().CGColor
self.layer.shadowOffset = CGSizeMake(0, 2)
self.layer.shadowRadius = 2
self.layer.shadowOpacity = 0.15

就像新闻提要一样,我的滚动视图有很多框,因此 UIView 有自己的阴影。如何在不减慢我的应用程序速度的情况下使用它?

设置 shadowPath 将提高性能,并且只要您的视图是不透明的,外观就会一样。您可以像这样将其设置为视图或图层的边界:

CGPathRef shadowPath = CGPathCreateWithRect(self.bounds, NULL);
self.layer.shadowPath = shadowPath;
CGPathRelease(shadowPath);

在Swift中:

layer.shadowPath = CGPathCreateWithRect(bounds, nil)

内存管理已为您处理(已讨论 here)。

有很多关于加速 UIScrollViews 的东西:

如果您使用自定义 CALayer 实例——尤其是阴影——需要处理能力的东西,您应该使用

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

还有一个 shadowPath 可以加速你的滚动视图,就像这样:

[scrollView.layer setShadowPath:[[UIBezierPath bezierPathWithRect:myView.bounds] CGPath]];

设置 shadowPath 允许 iOS 每次绘制视图时都不会重新计算应该如何绘制阴影,从而提高性能。

在 swift 中,是这样的:

let shadowPath = UIBezierPath(rect: view.bounds);
view.layer.masksToBounds = false;
view.layer.shadowColor = UIColor.blackColor().CGColor;
view.layer.shadowOffset = CGSizeMake(0, 0.5);
view.layer.shadowOpacity = 0.2;
view.layer.shadowPath = shadowPath.CGPath;