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

Bur*_*rak 7 core-animation fadeout ios

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

我应该使用渐变面膜吗?

rob*_*off 11

这是一种技术,可以淡化CALayer中的任何内容,从左上角到右下角,显示CALayer下面的任何内容.

假设我们将淡出UIImageView被调用的层self.fadeView.

我们将创建一个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
Run Code Online (Sandbox Code Playgroud)