Adding image to video, but it is distorted

I have UIView (see photo) and video (see video), I want to export this image to an image (see UIView to UIImage code) and add to the video (see "Add UIImage to video code"). But my result is not very good (see. Result). Please help me in this problem, thanks!

Photo

enter image description here

Video enter image description here

Result enter image description here

UIView for UIImage

UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

Add UIImage to Video

- (void)showImage:(UIImage*)img toCompostion:(AVMutableVideoComposition *)composition fromTime:(CGFloat)fromTime toTime:(CGFloat)toTime videoSize:(CGSize)size {
    CALayer *parentLayer = [CALayer layer];
    CALayer *viLayer = [CALayer layer];
    [parentLayer addSublayer:viLayer];

    parentLayer.frame = CGRectMake(0, 0, size.width, size.height);
    viLayer.frame = CGRectMake(0, 0, size.width, size.height);

    // 1 - set up the overlay
    CALayer *imgLayer = [CALayer layer];

    [imgLayer setContents:(id)[img CGImage]];
    imgLayer.frame = CGRectMake(50, 50, img.size.width, img.size.height); // Oxy: bottom left
    [imgLayer setMasksToBounds:YES];

    // 2 - set up the parent layer
    [parentLayer addSublayer:imgLayer];

    // the code for the opacity animation which then removes the image
    imgLayer.opacity = 0.0;
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    [animation setDuration:0.1]; //duration
    [animation setFromValue:[NSNumber numberWithFloat:0.0]];
    [animation setToValue:[NSNumber numberWithFloat:1.0]];
    [animation setBeginTime:fromTime]; // time to show text
    [animation setRemovedOnCompletion:NO];
    [animation setFillMode:kCAFillModeForwards];
    [imgLayer addAnimation:animation forKey:@"animateOpacity"];


    animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    [animation setDuration:0.1]; //duration
    [animation setFromValue:[NSNumber numberWithFloat:1.0]];
    [animation setToValue:[NSNumber numberWithFloat:0.0]];
    [animation setBeginTime:toTime]; // time to show text
    [animation setRemovedOnCompletion:NO];
    [animation setFillMode:kCAFillModeForwards];
    [imgLayer addAnimation:animation forKey:@"animateOpacity1"];
    ////

    // 3 - apply magic
    composition.animationTool = [AVVideoCompositionCoreAnimationTool
                                 videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:viLayer inLayer:parentLayer];

}

******** Update 1 ********
This is normal if I do this:
(1) change the scale of the UIGraphicsBeginImageContextWithOptions from 0.0 to 1.0.
(2) save the image to a file.
(3) Wait 0.01 seconds and return this file.
I do not know why I need to save the file.

+4
1

:

  • .

  • .

" " " "

+1

All Articles