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

我有一个UIView(见照片)和一个视频(见视频),我想将该视图导出到图像(参见“UIView to UI
Image”代码)并添加到视频(参见“添加UIImage到视频”代码).

但我的结果并不好(见结果).

请帮帮我这个问题,谢谢!

照片

《ios – 将图像添加到视频但它被扭曲了》

视频
《ios – 将图像添加到视频但它被扭曲了》

结果
《ios – 将图像添加到视频但它被扭曲了》

UIView到UIImage

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

UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

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

}

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

最佳答案 图像的失真仅在以下情况下发生,

>图像图层大小小于父图层的实际高度.
>图像的宽高比与图层的宽高比不匹配.

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

点赞