LoginSignup
29
28

More than 5 years have passed since last update.

文字色をグラデーションでアニメーション

Posted at

はじめに

24オープニングをプログラミングのみで再現したくなり
Xcodeを立ち上げ、ぽちぽちと作りました。

参考:
24 Opening Theme Song

まずはデジタルな文字の背景がアニメしている箇所のみを。

やっている内容は「アニメーションするグラデーション背景を文字型に切り抜き」とも言えます。

hvnv5.gif

アニメーションするグラデーション背景


- (void)insertGradientLayer:(UIView *)view
{
    UIColor *beginColor = [UIColor redColor];
    UIColor *endColor = [UIColor blueColor];

    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"colors"];
    animation.duration = 2.0;
    animation.repeatCount = HUGE_VALF;
    animation.autoreverses = YES;
    animation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut];
    animation.fromValue = @[(id)beginColor.CGColor, (id)endColor.CGColor];
    animation.toValue = @[(id)endColor.CGColor, (id)beginColor.CGColor];

    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = view.bounds;
    gradient.colors = @[(id)beginColor.CGColor, (id)endColor.CGColor];
    [gradient addAnimation:animation forKey:@"colors"];

    [view.layer insertSublayer:gradient atIndex:0];
}

文字マスクを作成し重ねる

UILabelをUIImage化し、マスク画像としています。
文字は黒色、背景は透明色です。

UIViewのUIImage変換は「関連」を参考にしてください。
有用な情報の共有ありがとうございます!


    UIView *gradientView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, 320, 300)];
    [self insertGradientLayer:gradientView];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 160)];
    label.font = [UIFont fontWithName:@"DBLCDTempBlack" size:144];
    label.textColor = [UIColor blackColor];
    label.text = @"24";
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    [self.view addSubview:label];

    UIImage *maskImage = [self imageFromView:label];
    CALayer *mask = [CALayer layer];
    mask.contents = (id)[maskImage CGImage];
    mask.frame = CGRectMake(0, 0, maskImage.size.width, maskImage.size.height);

    gradientView.layer.mask = label.layer;

    [self.view addSubview:gradientView];

おわりに

このプログラムはいつ完成するのか!
のんびりとした気持ちでお待ちください。

ちなみに24ではシーズン2が一番好きです。

参考

UIViewをUIImageに変換する

29
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
28