を作成していますがCAShapeLayer
、それに対して何も役に立ちません。それを修正しましょう。
でレイヤとアニメーションを設定しないでください-drawRect:
。CoreGraphics または UIKit API を使用して描画を行うための時間として厳密に意図されているためです。代わりに、CAShapeLayer で三角形を描画する必要があります。これにより、三角形をアニメーション化できます。
CAKeyframeAnimation.path は、まったく異なるもの (パスに沿ってレイヤーを移動するなど) を対象としています。
あなたのアニメーションはposition
レイヤーの値をアニメーション化しています。レイヤーが移動するのも当然です!path
代わりに値をアニメーション化します。
CAKeyframeAnimation の背後にある考え方はvalues
、レイヤーのプロパティを設定するための配列を提供することです。キーフレーム間の時間中、隣接する 2 つのキーフレーム間を補間します。そのため、複数のパス (各サイドに 1 つずつ) を指定する必要があります。
任意のパスを補間することは困難です。CA のパス補間は、パスに同じ数と同じ種類の要素がある場合に最適に機能します。そのため、すべてのパスが同じ構造を持ち、いくつかのポイントが互いに重なっているだけであることを確認します。
アニメーションの秘訣、そしておそらくコンピューター全般の秘訣は、何を実現したいかを正確に説明する必要があることです。「各ポイントの描画をアニメーション化したいので、アニメーション化されているように見えます」という情報はほとんどありません。
これは、あなたが求めていること、または少なくとも近いと思うUIView サブクラスです。アニメーション化するには、ボタンを-animate:
アクションに接続します。
SPAnimatedShapeView.h:
#import <UIKit/UIKit.h>
@interface SPAnimatedShapeView : UIView
- (IBAction)animate:(id)sender;
@end
SPAnimatedShapeView.m:
#import "SPAnimatedShapeView.h"
#import <QuartzCore/QuartzCore.h>
@interface SPAnimatedShapeView ()
@property (nonatomic, retain) CAShapeLayer* shapeLayer;
@end
@implementation SPAnimatedShapeView
@synthesize shapeLayer = _shapeLayer;
- (void)dealloc
{
[_shapeLayer release];
[super dealloc];
}
- (void)layoutSubviews
{
if (!self.shapeLayer)
{
self.shapeLayer = [[[CAShapeLayer alloc] init] autorelease];
self.shapeLayer.bounds = CGRectMake(0, 0, 100, 100); // layer is 100x100 in size
self.shapeLayer.position = self.center; // and is centered in the view
self.shapeLayer.strokeColor = [UIColor blueColor].CGColor;
self.shapeLayer.fillColor = [UIColor redColor].CGColor;
self.shapeLayer.lineWidth = 3.f;
[self.layer addSublayer:self.shapeLayer];
}
}
- (IBAction)animate:(id)sender
{
UIBezierPath* path0 = [UIBezierPath bezierPath];
[path0 moveToPoint:CGPointZero];
[path0 addLineToPoint:CGPointZero];
[path0 addLineToPoint:CGPointZero];
[path0 addLineToPoint:CGPointZero];
UIBezierPath* path1 = [UIBezierPath bezierPath];
[path1 moveToPoint:CGPointZero];
[path1 addLineToPoint:CGPointMake(50,100)];
[path1 addLineToPoint:CGPointMake(50,100)];
[path1 addLineToPoint:CGPointMake(50,100)];
UIBezierPath* path2 = [UIBezierPath bezierPath];
[path2 moveToPoint:CGPointZero];
[path2 addLineToPoint:CGPointMake(50,100)];
[path2 addLineToPoint:CGPointMake(100,0)];
[path2 addLineToPoint:CGPointMake(100,0)];
UIBezierPath* path3 = [UIBezierPath bezierPath];
[path3 moveToPoint:CGPointZero];
[path3 addLineToPoint:CGPointMake(50,100)];
[path3 addLineToPoint:CGPointMake(100,0)];
[path3 addLineToPoint:CGPointZero];
CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"path"];
animation.duration = 4.0f;
animation.values = [NSArray arrayWithObjects:(id)path0.CGPath, (id)path1.CGPath, (id)path2.CGPath, (id)path3.CGPath, nil];
[self.shapeLayer addAnimation:animation forKey:nil];
}
@end