如何在ios sdk中使用动画增加和减少图像alpha值?

时间:2013-09-06 12:32:39

标签: iphone ios

在这段代码中我使用的是动画。但是我一次也需要更改图像的alpha值。

-(void)animation
{
    CGPoint point = CGPointMake(imgView.frame.origin.x, imgView.frame.origin.y);
    imgView.layer.position = point;
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position.x"];
    anim.fromValue  = [NSValue valueWithCGPoint:point];
    anim.toValue    = [NSValue valueWithCGPoint:CGPointMake(point.x + 50, point.y)];
    anim.duration   = 10.0f;
    anim.repeatCount =1;
    anim.removedOnCompletion = YES;

    anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];

    [imgView.layer addAnimation:anim forKey:@"position.x"];
    imgView.layer.position = point;
}

5 个答案:

答案 0 :(得分:6)

您可以使用opacity的{​​{1}}键执行此操作:

CABasicAnimation

修改

要通过指定值制作动画,您可以使用CABasicAnimation *alphaAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"]; alphaAnimation.fromValue = [NSNumber numberWithFloat:1.0]; alphaAnimation.toValue = [NSNumber numberWithFloat:0.0]; [imgView.layer addAnimation:alphaAnimation forKey:@"opacity"];

CAKeyframeAnimation

答案 1 :(得分:1)

为了减少alpha与视图的x位置相同的时间/速率,只需将位置设置代码与alpha设置代码放在同一个动画块中,如下所示:

CGPoint finalPoint = CGPointMake(500, imgView.center.y); //change for any final point you want
CGFloat finalAlpha = 0.0; //change the final alpha as you want
UIView animateWithDuration:1.0 animations:^{ //change the duration as you want
   imgView.alpha = finalAlpha; 
   imgView.center = finalPoint;
}];

答案 2 :(得分:0)

//your code of changing x position will be here 

现在实现我的代码,如下所示。

 UIView animateWithDuration:1.0 animations:^{
imgView.alpha = 0.5;//must be in between 0 to 1
 }];

现在当你的imageview移动到下一个位置时,请写下面的代码

//下一个位置的imageview代码.. 现在实现下面的代码...

 UIView animateWithDuration:0.5 animations:^{
imgView.alpha = 1.0;//must be in between 0 to 1
 }];

让我知道它的工作与否!!!!希望它有所帮助...

快乐编码!!!

答案 3 :(得分:0)

这在500毫秒内“逐渐消失”self.view

在调用它之前你做的任何事情都会被“立即”设置,你在“动画”块中设置的所有东西(比如设置新的帧坐标)都会在指定的持续时间内进行插值。

        [UIView animateWithDuration:0.50
                              delay:0.0
                            options:(   UIViewAnimationOptionAllowUserInteraction
                                     |  UIViewAnimationOptionBeginFromCurrentState
                                     |  UIViewAnimationOptionCurveEaseInOut)

                         animations:^ {
                             self.view.alpha = 0.0f ;
                         }

                         completion: ^(BOOL){
                             [self.view removeFromSuperview] ;
                             self.view = nil ;
                         }
         ] ;

答案 4 :(得分:0)

您可以使用CABasicAnimation对象(不同的对象,因为您将为其设置动态不同的KeyPath,即alpha),并使用NSNumbers作为fromValue和{ {1}}。

另一种(也是最简单的)方法是使用专用于动画的toValue辅助方法(UIView和所有),特别是如果你必须同时为多个属性设置动画(你可以设置两者的动画效果) animateWithDuration:…frame具有相同的动画块(如果它符合您的需求并简化您的代码)。

您还可以混合alpha用于框架,CABasicAnimation用于Alpha,无论您需要什么组合,具体取决于您的动画是否复杂且需要自定义(自定义计时功能,非线性动画) ,...)或不。