将图像添加到视频但它被扭曲了

hun*_*m06 5 objective-c video-processing ios

我有一个 UIView(参见照片)和一个视频(参见视频),我想将该视图导出为图像(参见“UIView 到 UIImage”代码)并添加到视频(参见“将 UIImage 添加到视频”代码)。但我的结果并不好(见结果)。请帮我解决这个问题,谢谢!

照片

在此处输入图片说明

视频 在此处输入图片说明

结果 在此处输入图片说明

UIView 到 UIImage

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

UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)

将 UIImage 添加到视频

- (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];

}
Run Code Online (Sandbox Code Playgroud)

********更新 1********
如果我这样做可以:
(1) 将 UIGraphicsBeginImageContextWithOptions 的比例从 0.0 更改为 1.0。
(2) 将图像保存到文件。
(3) 等待 0.01 秒并读回该文件。
我不知道为什么需要保存到文件????

Rat*_*ran 0

图像失真仅发生在以下情况,

  1. 图像层大小小于父层的实际高度。

  2. 图像的长宽比与图层的长宽比不匹配。

在您的代码中检查“父层”框架大小和“图像层”框架