你可以很容易地使用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