你可以很容易地使用CALayerShape用钢笔形象和做这样的(我添加了一个按钮,从而引发了图纸的视图):
#import "ViewController.h"
@interface ViewController() {
UIBezierPath *_drawPath;
CALayer *_pen;
UIBezierPath *_penPath;
CAShapeLayer *_rectLayer;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIImage *penImage = [UIImage imageNamed:@"pen"];
_drawPath = [UIBezierPath bezierPathWithRect:self.view.frame];
_penPath = [UIBezierPath bezierPath];
[_penPath moveToPoint:CGPointMake(penImage.size.width/2.f, penImage.size.height/2.f)];
[_penPath addLineToPoint:CGPointMake(self.view.frame.size.width - penImage.size.width/2.f, penImage.size.height/2.f)];
[_penPath addLineToPoint:CGPointMake(self.view.frame.size.width - penImage.size.width/2.f, self.view.frame.size.height - penImage.size.height/2.f)];
[_penPath addLineToPoint:CGPointMake(penImage.size.width/2.f, self.view.frame.size.height - penImage.size.height/2.f)];
[_penPath addLineToPoint:CGPointMake(penImage.size.width/2.f, penImage.size.height/2.f)];
_rectLayer = [[CAShapeLayer alloc] init];
_rectLayer.path = _drawPath.CGPath;
_rectLayer.strokeColor = [UIColor greenColor].CGColor;
_rectLayer.lineWidth = 5.f;
_rectLayer.fillColor = [UIColor clearColor].CGColor;
_rectLayer.strokeEnd = 0.f;
[self.view.layer addSublayer:_rectLayer];
_pen = [CALayer layer];
_pen.bounds = CGRectMake(0, 0, 25.f, 25.f);
_pen.position = CGPointMake(penImage.size.width/2.f, penImage.size.height/2.f);
_pen.contents = (id)(penImage.CGImage);
_pen.position = CGPointMake(penImage.size.width/2.f, penImage.size.height/2.f);
[self.view.layer addSublayer:_pen];
}
- (IBAction)drawRectangle:(id)sender
{
_rectLayer.strokeEnd = 1.f;
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
anim.fromValue = (id)[NSNumber numberWithFloat:0];
anim.toValue = (id)[NSNumber numberWithFloat:1.f];
anim.duration = 5.f;
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[_rectLayer addAnimation:anim forKey:@"drawRectStroke"];
CAKeyframeAnimation *penMoveAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
penMoveAnimation.path = _penPath.CGPath;
penMoveAnimation.rotationMode = kCAAnimationRotateAuto;
penMoveAnimation.duration = 5.0;
penMoveAnimation.calculationMode = kCAAnimationPaced;
[_pen addAnimation:penMoveAnimation forKey:@"followStroke"];
}
编辑:添加代码笔跟踪行程,继承人所使用的2x图像:http://cl.ly/image/173J271Y003B
注意:唯一的问题是,当笔接近旋转点或转角时,它仍然与笔画同步,因此笔看起来像是在笔画的后面,直到它翻转,一个简单的解决方案可能是曲线,但林不知道你的总体目标是什么。
你会如何保持笔图像与动画同步?我认为这是缺少答案的重要部分。 –
将此标记为正确,但正如Brad所示,知道是否有将UIImageView与动画同步的方法会很有趣。 – soleil