Kaitis
Kaitis

Reputation: 638

Add a text layer to video at specific time

I want to add a text layer to a video for the last 4 seconds of the video. This is what i have so far:

// 1 - Set up the watermark text layer
    CATextLayer *waterMarkText = [[CATextLayer alloc] init];
    [waterMarkText setFont:@"Helvetica-Neue"];
    [waterMarkText setFontSize:30];
    [waterMarkText setFrame:CGRectMake(0, 0, self.size.width, 80)];
    [waterMarkText setString:@"made with Videofy"];
    [waterMarkText setAlignmentMode:kCAAlignmentRight];
    [waterMarkText setForegroundColor:[[UIColor whiteColor] CGColor]];

//Fade In the watermark
    CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];

    fadeInAnimation.duration = 2;
    fadeInAnimation.fromValue = [NSNumber numberWithFloat:0.0];
    fadeInAnimation.toValue = [NSNumber numberWithFloat:1.0];
    fadeInAnimation.beginTime = videoDuration - 4;
    fadeInAnimation.removedOnCompletion = NO;
    [overlayLayer addAnimation:fadeInAnimation forKey:@"animateOpacity"];

The animation is added to the final video but the watermark is visible from the beginning of the video. How can I set the opacity to 0 before the animation starts?

(I have tried setting the opacity of the watermarkText to 0 but that seems to override the animation. )

Upvotes: 4

Views: 1383

Answers (1)

Nare Muradyan
Nare Muradyan

Reputation: 91

So for the appearing and disappearing to work you will need to add two animations - one for each. Here is a sample code that works for me. In this particular case I add a text layer from 0 to 1 seconds of the video. You should put your own values for the begin times of animations. You should set the opacity to 0 in the beginning.

        textLayer.opacity = 0

        let startVisible = CABasicAnimation(keyPath: "opacity")
        startVisible.duration = 0.1 // for appearing in duration
        startVisible.repeatCount = 1
        startVisible.fromValue = 0.0
        startVisible.toValue = 1.0
        startVisible.beginTime = 0.0 // overlay time range start second
        startVisible.isRemovedOnCompletion = false
        startVisible.fillMode = CAMediaTimingFillMode.forwards
        textLayer.add(startVisible, forKey: "startAnimation")

        let endVisible = CABasicAnimation(keyPath: "opacity")
        endVisible.duration = 0.1 // for disappearing in duration
        endVisible.repeatCount = 1
        endVisible.fromValue = 1.0
        endVisible.toValue = 0.0
        endVisible.beginTime = 1.0 // overlay time range end second
        endVisible.fillMode = CAMediaTimingFillMode.forwards
        endVisible.isRemovedOnCompletion = false
        textLayer.add(endVisible, forKey: "endAnimation")

Upvotes: 3

Related Questions