ios - 如何在 IOS 中应用部分淡入淡出?

标签 ios core-animation fadeout

我有 2 张图片。一个在另一个的后面。我想从左上角开始淡出顶部图像。我怎样才能做到这一点?

我应该使用渐变 mask 吗?

最佳答案

这是一种技术,可以淡出 CALayer 中的所有内容,从左上角到右下角,显示 CALayer 下方的内容。

假设我们要淡出名为 self.fadeViewUIImageView 层。

我们将创建一个 CAGradientLayer并将其用作 self.fadeView.layer.mask。渐变将从 alpha=0(透明)变为 alpha=1(不透明),使用四个停止点:0、0、1、1。是的,两个零,然后是两个一。当我们希望 fadeView 不透明时,我们将停止位置设置为 -1、-.5、0、1。这样两个 alpha=0 停止点就完全在层边界之外。当我们希望 fadeView 透明时,我们将停止位置设置为 0、1、1.5、2。这样两个 alpha=1 停止点就完全在层边界之外。 CAGradientLayer 将自动对其停止位置的变化进行动画处理,从而创建交叉淡入淡出效果。

代码如下:

#import "ViewController.h"

@implementation ViewController

@synthesize fadeView = _fadeView;

static NSArray *locations(float a, float b, float c, float d)
{
    return [NSArray arrayWithObjects:
        [NSNumber numberWithFloat:a],
        [NSNumber numberWithFloat:b],
        [NSNumber numberWithFloat:c],
        [NSNumber numberWithFloat:d],
        nil];
}

// In my test project, I put a swipe gesture recognizer on fadeView in my XIB
// with direction = Up and connected it to this action.
- (IBAction)fadeIn
{
    [CATransaction begin];
    [CATransaction setValue:[NSNumber numberWithDouble:2.0] forKey:kCATransactionAnimationDuration];
    ((CAGradientLayer *)self.fadeView.layer.mask).locations = locations(-1, -.5, 0, 1);
    [CATransaction commit];
}

// In my test project, I put a swipe gesture recognizer on fadeView in my XIB
// with direction = Down and connected it to this action.
- (IBAction)fadeOut
{
    [CATransaction begin];
    [CATransaction setValue:[NSNumber numberWithDouble:2.0] forKey:kCATransactionAnimationDuration];
    ((CAGradientLayer *)self.fadeView.layer.mask).locations = locations(0, 1, 1.5, 2);
    [CATransaction commit];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    CAGradientLayer *mask = [CAGradientLayer layer];
    mask.frame = self.fadeView.bounds;
    mask.colors = [NSArray arrayWithObjects:
        (__bridge id)[UIColor clearColor].CGColor,
        (__bridge id)[UIColor clearColor].CGColor,
        (__bridge id)[UIColor whiteColor].CGColor,
        (__bridge id)[UIColor whiteColor].CGColor,
        nil];
    mask.startPoint = CGPointZero; // top left corner
    mask.endPoint = CGPointMake(1, 1); // bottom right corner
    self.fadeView.layer.mask = mask;
    [self fadeIn]; // initialize mask.locations
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

关于ios - 如何在 IOS 中应用部分淡入淡出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8346837/

相关文章:

ios - 使用同一按钮播放/暂停

ios - Objective-C 解码引用的可打印文本

iphone - ios url从邮件重定向到应用程序

cocoa - 图层托管 View 不显示

jquery - 如何停止 jQuery 淡入淡出/淡出连续循环?

ios - UIButton 圆角半径在 CustomClass 中无法正常工作

objective-c - 为什么 Core Animation 方法是类方法而不是实例方法?

ios - 核心动画 setFromValue

jquery - 淡出+清空div,然后放入新内容

jquery - 是否有一个 jquery 插件可以根据点击时的类(类别)显示/隐藏 div