CALayer - Shadow causes a performance hit?

2019-01-21 17:01发布

So I am doing some custom animations on my navigationcontroller and the way it pushes and pops the viewControllers.

Everything runs smooth. As soon as I add the following code (In a subclass of UINavigationController), I face a huge performance hit. After adding a shadow all animations become very laggy. Is this expected or am I doing something wrong in the code?

// This code gets called once during NavigationController initialization.
[self.view setClipsToBounds:NO];
[self.view.layer setCornerRadius:5];
[self.view.layer setShadowOffset:CGSizeMake(0, 20)];
[self.view.layer setShadowColor:[[UIColor yellowColor] CGColor]];
[self.view.layer setShadowRadius:20.0];
[self.view.layer setShadowOpacity:1];

EDIT:

Changed my shadow radius to 1 and it's still slow

4条回答
爷的心禁止访问
2楼-- · 2019-01-21 17:09

You should expect a slowdown from adding a shadow. A shadowRadius of 20 is very high and will be especially slow.

The other key to improve shadow rendering speed: set the shadowPath property. It can help dramatically.

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-21 17:12

Yes, shadow's are very expensive (especially a shadow that big -- play with the radius and you'll notice it makes a huge difference in the degree of slowdown you experience). One way to improve performance is to render it once to a CGImageContext and just display that image instead of having the layer re-render the shadow every time it redraws (but this doesn't work if the shadow needs to animate or something).

查看更多
手持菜刀,她持情操
4楼-- · 2019-01-21 17:17

Using shadowPath instead of shadowOffset.

theView.layer.shadowPath = [UIBezierPath bezierPathWithRect:theView.bounds].CGPath;

Check this post: iphone - Animation's performance is very poor when view's shadow is on

查看更多
放荡不羁爱自由
5楼-- · 2019-01-21 17:23
self.view.layer.shouldRasterize = YES;
self.view.layer.rasterizationScale = UIScreen.mainScreen.scale;

I was recently having some issues with slow CALayer shadows, and that simple line of code fixed up everything for me!

查看更多
登录 后发表回答