我正在使用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];
。否则,请参阅此帖子.
编辑后的回复
使用核心动画,您可以在按钮背后执行类似于以下内容的操作:
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;
}
这只是指向使用核心动画的一些示例。详情请参见此文章。
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")