【问题标题】:Animating a UIImageView tint动画 UIImageView 色调
【发布时间】:2010-12-27 00:06:47
【问题描述】:

类似于this previous question,我想将任意颜色的色调应用于任意图像(UIImageView)。但是,我希望色彩在 N 秒内消失,以产生“脉冲”效果。我将每 M 秒触发一次脉冲。

虽然我认为我可以使用 NSTimer 来构建一个简单的解决方案来更改色调,但我认为我可能可以使用一些 Core Animation 框架来获得一个更优雅(和高效)的解决方案。但是,我对 Core Animation 不是很熟悉。

Core Animation 可以创建这样的“脉冲”吗?如果有,怎么做?

【问题讨论】:

    标签: iphone core-animation uiimageview


    【解决方案1】:

    聚会迟到了,但我找到了为UIImageViewtintColor 制作动画的方法。您只需为CABasicAnimation 提供contentsMultiplyColor 作为keyPath。示例:

    // 5 seconds infinite pulse animation from current tintColor to red color
    let basicAnimation = CABasicAnimation(keyPath: "contentsMultiplyColor")
    basicAnimation.duration = 5.0 
    basicAnimation.fromValue = imageView.tintColor.cgColor
    basicAnimation.toValue = UIColor.red.cgColor
    basicAnimation.autoreverses = true
    basicAnimation.repeatCount = Float.infinity
    
    imageView.layer.add(basicAnimation, forKey: "TintColorAnimationKey")
    

    【讨论】:

      【解决方案2】:

      如果您打算使用 Core Animation,则该方法将不同于您在上一个 SO 问题的链接中演示的方法。相反,创建一个使用您所追求的颜色作为色调的图层,然后对该图层的不透明度进行动画处理。像这样的:

      CALayer *tintLayer = [CALayer layer];
      
      // Center the layer on the view
      [tintLayer setBounds:[imageView bounds]];
      [tintLayer setPosition:CGPointMake([imageView bounds].size.width/2.0, 
                                         [imageView bounds].size.height/2.0)];
      
      // Fill the color
      [tintLayer setBackgroundColor:
                 [[UIColor colorWithRed:0.5 green:0.5 blue:0.0 alpha:1.0] CGColor]];
      [tintLayer setOpacity:0.5];
      [[imageView layer] addSublayer:tintLayer];
      
      // Add the animation
      CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
      [animation setFromValue:[NSNumber numberWithFloat:0.5]];
      [animation setToValue:[NSNumber numberWithFloat:0.0]];
      // Animate back to the starting value automatically
      [animation setAutoreverses:YES];
      // Animate over the course of 5 seconds.
      [animation setDuration:5.0];
      
      [tintLayer addAnimation:animation forKey:@"opacity"];
      

      我不确定的唯一问题是它是否会起作用,因为我们没有在色调层中指定混合模式。我将不得不查看默认情况下与 CA 发生的混合情况。

      最好的问候。

      更新:发现 another SO 帖子说 CA 中的混合取决于图层的“不透明”属性。

      【讨论】:

      • 如果上述任意图像不是矩形(如圆形),或者只是在其周围有空白边框(0 alpha 的像素),这会起作用吗?因为如果你调用 setBackgroundColor:,你将为那些不应该被“点亮”的像素设置颜色。
      • 对,它将为整个矩形着色。不过,我认为其他核心图形方法也是如此。不过,我不确定,因为我还没有尝试过。
      • 您可以为 tintLayer 添加蒙版。我正在考虑为 UIImageView 着色 - tintLayer.mask = imageView.layer 可能会成功。希望 imageView.layer 喜欢在两个地方使用。
      猜你喜欢
      • 2023-03-19
      • 2012-02-09
      • 2018-06-16
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      • 2010-09-30
      相关资源
      最近更新 更多