UIView サブクラス (MyView と呼ばれる) の (void)drawRect:(CGRect)rect で単純なオブジェクトをアニメーション化する方法を理解しようとしています。私はコア アニメーションに不慣れで、このようなことを行う最善の方法がわかりません。
私は基本的に、タッチ座標をキャプチャして、動くオブジェクトとして表現できるようにしたいと考えています。NSMutableArray を使用してタッチをうまく保存できます。
Core Animation Programming Guide と Quartz2D Programming Guide を読むのに多くの時間を費やしました。サブレイヤーとレイヤーの使用に精通しているので、これがこのようなものに使用する必要がある場合は、正しい方向に向けてください。
私の主な目標は、タッチ ポイントをキャプチャして、移動可能な任意の形状として表現できるようにすることです。どんな助けでも大歓迎です。
#import "MyView.h"
@implementation MyView
@synthesize lastPoint;
NSMutableArray *myPoints;
CADisplayLink *theTimer;
float position = 0;
- (void) initializeTimer
{
theTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(animateStuff:)];
theTimer.frameInterval = 2; // run every other frame (ie 30fps)
[theTimer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
- (void) animateStuff:(NSTimer *)theTimer
{
position++;
[self setNeedsDisplay];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (id)initWithCoder:(NSCoder *)decoder
{
if ((self = [super initWithCoder:decoder])) {
// init array
myPoints = [NSMutableArray array];
position = 1;
[self initializeTimer];
}
return self;
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
// store point in array
UITouch *touch = [touches anyObject];
lastPoint = [touch locationInView:self];
[myPoints addObject:[NSValue valueWithCGPoint:lastPoint]]; // store CGPoint as NSValue
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor orangeColor].CGColor);
// draw all points in array
NSUInteger pointCount = [myPoints count];
for (int i = 0; i < pointCount; i++) {
NSValue *v = [myPoints objectAtIndex:i];
CGPoint p = v.CGPointValue;
CGRect currentRect = CGRectMake(p.x-10+position, p.y-10, 20, 20);
CGContextAddRect(context, currentRect);
}
CGContextDrawPath(context, kCGPathFillStroke);
}
@end