【发布时间】:2011-10-24 14:25:47
【问题描述】:
我正在使用 CGContextRef 在 iphone 中画线。谁能建议我如何在 iphone 中用动画画线。
请提出建议。
【问题讨论】:
我正在使用 CGContextRef 在 iphone 中画线。谁能建议我如何在 iphone 中用动画画线。
请提出建议。
【问题讨论】:
这是答案(在这里找到:http://soulwithmobiletechnology.blogspot.fr/2012/07/how-to-animate-line-draw.html)
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(50.0,0.0)];
[path addLineToPoint:CGPointMake(120.0, 600.0)];
CAShapeLayer *pathLayer = [CAShapeLayer layer];
pathLayer.frame = self.view.bounds;
pathLayer.path = path.CGPath;
pathLayer.strokeColor = [[UIColor redColor] CGColor];
pathLayer.fillColor = nil;
pathLayer.lineWidth = 2.0f;
pathLayer.lineJoin = kCALineJoinBevel;
[self.view.layer addSublayer:pathLayer];
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 2.0;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];
别忘了#import <QuartzCore/QuartzCore.h>。
【讨论】:
它是一条直线吗?.. 您可以使用 1 像素宽的 UIView 并为其 frame 属性设置动画。使用[UIView beginAnimations] 和[UIView commitAnimations]; 否则,see this post。
修改后的回复
使用核心动画,你可以做这样的事情(例如在按钮后面)
CABasicAnimation *theAnimation = [self pathAnimation];
theAnimation.duration=3.0;
theAnimation.autoreverses=YES;
[[self layer] addAnimation:theAnimation forKey:@"animatePath"];
路径动画定义为:
- (CAAnimation*)pathAnimation;
{
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path,NULL,50.0,120.0);
CGPathAddCurveToPoint(path,NULL,50.0,275.0,
150.0,275.0,
150.0,120.0);
CGPathAddCurveToPoint(path,NULL,150.0,275.0,
250.0,275.0,
250.0,120.0);
CGPathAddCurveToPoint(path,NULL,250.0,275.0,
350.0,275.0,
350.0,120.0);
CGPathAddCurveToPoint(path,NULL,350.0,275.0,
450.0,275.0,
450.0,120.0);
CAKeyframeAnimation *
animation = [CAKeyframeAnimation
animationWithKeyPath:@"position"];
[animation setPath:path];
[animation setDuration:3.0];
[animation setAutoreverses:YES];
CFRelease(path);
return animation;
}
这只是一个指向您可以使用 Core Animation 做什么的指针。详情请见this article。
【讨论】:
Martin 答案的 Swift 3 版本(使用 Xcode 8.3.3 检查)
let path = UIBezierPath()
path.move(to: CGPoint(x: 50, y: 0))
path.addLine(to: CGPoint(x: 120, y: 600))
let pathLayer = CAShapeLayer()
pathLayer.frame = view.bounds
pathLayer.path = path.cgPath
pathLayer.strokeColor = UIColor.red.cgColor
pathLayer.fillColor = nil
pathLayer.lineWidth = 2
pathLayer.lineJoin = kCALineJoinBevel
view.layer.addSublayer(pathLayer)
let pathAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathAnimation.duration = 2.0
pathAnimation.fromValue = 0
pathAnimation.toValue = 1
pathLayer.add(pathAnimation, forKey: "strokeEnd")
【讨论】: