【问题标题】:How to adjust drop shadow dynamically during an UIImageView rotation?如何在 UIImageView 旋转期间动态调整阴影?
【发布时间】:2011-10-24 19:04:50
【问题描述】:

我使用以下代码来添加阴影:

letterE.layer.shadowColor = [[UIColor blackColor] CGColor];
letterE.layer.shadowOffset = CGSizeMake(2.5, 2.5);
letterE.layer.shadowRadius = 3.0;
letterE.layer.shadowOpacity = 0.95;

以及以下要旋转的内容:

CABasicAnimation* rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0];
rotationAnimation.duration = 5.0;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = 1.0; 
rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];

[letterE.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];

在动画期间,阴影是静态的,看起来很奇怪:

如何让阴影在动画过程中动态更新?

【问题讨论】:

    标签: iphone cocoa-touch uikit core-animation core-graphics


    【解决方案1】:

    我觉得这很有趣,所以我试了一下。一种可能的解决方案是在主视图下构建第二个清晰视图,使用原始视图的路径为其(底部视图)提供阴影。然后您可以将动画应用于两个视图。我用简单的矩形视图做到了这一点,但我看不出为什么不能用更复杂的路径或使用 2 个 CALayers 而不是 2 个 UIView 来完成。

    这就是我设置视图的方式...

    testView = [[UIView alloc] initWithFrame:CGRectMake(40, 40, 100, 100)];
    testView.backgroundColor = [UIColor redColor];
    
    //increase y origin of second view to simulate shadow offset
    testViewShadow = [[UIView alloc] initWithFrame:CGRectMake(40, 50, 100, 100)];
    
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0, 0, testView.frame.size.width, testView.frame.size.height)); 
    testViewShadow.layer.shadowPath = path;
    testViewShadow.layer.shadowOpacity = 1.0;
    testViewShadow.layer.shadowOffset = CGSizeMake(0, 0);
    testViewShadow.layer.shadowRadius = 10.0;
    CFRelease(path);
    
    [self.view addSubview:testViewShadow];
    [self.view addSubview:testView];
    

    ..还有我的动画(只是将您的 CAAnimation 作为 IBAction 连接到按钮并应用于两个视图)...

    - (IBAction)rotate:(id)sender{
        CABasicAnimation* rotationAnimation;
        rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0];
        rotationAnimation.duration = 5.0;
        rotationAnimation.cumulative = YES;
        rotationAnimation.repeatCount = 1.0; 
        rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    
        [testView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
        [testViewShadow.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    }
    

    这就是结果的样子……

    如果您将它们应用于两个视图,任何 (2D) 转换都应该看起来可信。

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 2021-02-09
      • 2011-08-12
      • 2022-01-10
      • 1970-01-01
      • 2015-10-12
      • 2016-10-16
      • 2021-11-19
      • 1970-01-01
      • 2017-02-04
      相关资源
      最近更新 更多