gpt4 book ai didi

iphone - 无法使用 CALayer for iphone 创建 ken burns 效果

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:45:52 24 4
gpt4 key购买 nike

最近几天我一直在尝试使用带有动画的 CALayer 创建 ken burns 效果,然后将其保存到视频文件中。

我的图像层位于另一个 1024x576 的层内。所有动画都应用于图像层。

这是目前的代码:

- (CALayer*)buildKenBurnsLayerWithImage:(UIImage *)image startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint fromScale:(float)fromScale toScale:(float)toScale
{
float calFromScale = fromScale + 1;
float calToScale = toScale + 1;
float fromX = startPoint.x * calFromScale;
float fromY = (image.size.height * calFromScale) - (videoSize.height + (startPoint.y * calFromScale));
float toX = endPoint.x * calToScale;
float toY = (image.size.height * calToScale) - (videoSize.height + (endPoint.y * calToScale));

CGPoint anchor = CGPointMake(0.0, 0.0);

CALayer* imageLayer = [CALayer layer];
imageLayer.contents = (id)image.CGImage;
imageLayer.anchorPoint = anchor;
imageLayer.bounds = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
imageLayer.position = CGPointMake(image.size.width * anchor.x, image.size.height * anchor.y);
imageLayer.contentsGravity = kCAGravityResizeAspect;

// create the panning animation.
CABasicAnimation* panningAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
panningAnimation.fromValue = [NSValue valueWithCGPoint:CGPointMake(-fromX, -fromY)];
panningAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(-toX, -toY)];
panningAnimation.additive = YES;
panningAnimation.removedOnCompletion = NO;

// create the scale animation.
CABasicAnimation* scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
scaleAnimation.fromValue = [NSNumber numberWithFloat:fromScale];
scaleAnimation.toValue = [NSNumber numberWithFloat:toScale];
scaleAnimation.additive = YES;
scaleAnimation.removedOnCompletion = NO;

CAAnimationGroup* animationGroup = [CAAnimationGroup animation];
animationGroup.animations = [[NSMutableArray alloc] initWithObjects:panningAnimation,scaleAnimation, nil];
animationGroup.beginTime = 1e-100;
animationGroup.duration = 5.0;
animationGroup.removedOnCompletion = NO;
animationGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

[imageLayer addAnimation:animationGroup forKey:nil];

return imageLayer;
}

下面是我调用方法的方式:

CALayer* animatedLayer = [self buildKenBurnsLayerWithImage:image startPoint:CGPointMake(100, 100) endPoint:CGPointMake(500, 500) fromScale:5.0 toScale:2.0];

我遇到的问题是平移和缩放的最终结果在屏幕上偏移了几个像素。

如果有人知道如何解决这个问题,我将不胜感激。

最佳答案

所有的变换都是针对 anchor 应用的。尝试使用 anchor

CGPoint anchor = CGPointMake(0.5f, 0.5f);

您的“视口(viewport)”不应再向右下角缩放(如果这是导致动画偏离几个像素的原因),而是向所有方向缩放。

关于iphone - 无法使用 CALayer for iphone 创建 ken burns 效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9442957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com