我试图了解如何在我的 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