为CALayer的shadowPath设置动画时的平滑动画

mat*_*ven 6 animation core-animation objective-c uikit ios

在我的应用程序中,我有一个UIView正在使用CALayer以实现阴影:

@implementation MyUIView

    - (instancetype) initWithFrame:(CGRect)frame {
        self = [super initWithFrame:frame];
        if(!self) return self;

        self.layer.shadowColor = [UIColor colorWithWhite:0 alpha:.2].CGColor;
        self.layer.shadowOffset = CGSizeMake(0, 2);
        self.layer.shadowOpacity = 1;
        self.layer.shadowRadius = 1;

        return self;
    }

@end
Run Code Online (Sandbox Code Playgroud)

如果我想要任何接近合理性能的东西,我必须定义CALayer's shadowPath:

@implementation MyUIView

    - (void) setFrame:(CGRect)frame {
        [super setFrame:frame];

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

@end
Run Code Online (Sandbox Code Playgroud)

每当我制作动画时,我都注意到了两件事UIView:

  1. 如果我使用a shadowPath,阴影会随着旋转和帧大小的变化而很好地动画.这里需要注意的是动画速度非常慢,而且性能普遍不足.

  2. 如果我做的使用shadowPath只要UIView是动画的动画是顺利和及时,但阴影的过渡本身更加块状(和欠光滑),比它是没有shadowPath.

例子:

编辑:

值得注意的是,这些动画是隐含的 - 我不是自己调用它们.它们是UIViewController设备方向旋转的结果.阴影UIView在旋转期间会改变大小.

Den*_*nis 4

我尝试重现您提供的两个 gif 中显示的行为,但没有成功(也许您可以使用动画代码编辑您的问题,例如UIView animateWithDuration:animations:)。

然而,在我脑海深处的某个地方,我记得我偶尔遇到过类似的问题,结果我必须对视图进行栅格化以使其平滑。

所以我不能保证它能解决您的问题,但请尝试一下:

self.layer.shouldRasterize = YES;
self.layer.rasterizationScale = [[UIScreen mainScreen] scale];
Run Code Online (Sandbox Code Playgroud)