Mac OSX - 核心动画 - 如何动画跟随我的光标的东西?

时间:2013-04-18 07:08:38

标签: cocoa core-animation

到目前为止,我只看到Core Animation的代码看起来像这样,其中动画的位置参数在开头设置。

- (void) startTopLeftImageViewAnimation{
/* Start from top left corner */ 
[self.xcodeImageView1 setFrame:CGRectMake(0.0f,0.0f, 100.0f, 100.0f)];
[self.xcodeImageView1 setAlpha:1.0f];
[UIView beginAnimations:@"xcodeImageView1Animation" context:(__bridge void *)self.xcodeImageView1];
/* 3 seconds animation */
[UIView setAnimationDuration:3.0f];
/* Receive animation delegates */ [UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector: @selector(imageViewDidStop:finished:context:)];
/* End at the bottom right corner */ [self.xcodeImageView1 setFrame:CGRectMake(220.0f,
350.0f, 100.0f,
[self.xcodeImageView1 setAlpha:0.0f];
[UIView commitAnimations]; 
}

但是,我想制作一个动画,其中图形跟随我的鼠标光标。这意味着动画不断接收我的鼠标指针x-y值。

有没有更好的替代做这样的“手动”动画,并且每当我移动鼠标的位置时调用drawRect?我可以使用Core Animation吗?

- (void)drawRect:(NSRect)rect
{
    // Drawing code here.
    [[NSColor whiteColor] set];
    NSRectFill( rect );

    [self drawCircleAtPoint:_circlePt];
}

- (void) drawCircleAtPoint:(CGPoint) point {

    NSBezierPath* thePath = [NSBezierPath bezierPath];
    NSRect nrect = NSMakeRect(point.x, point.y, 50, 50);
    [thePath appendBezierPathWithOvalInRect:nrect];
    [[NSColor blackColor] set];
    [thePath stroke];
}

感谢您对此提供任何帮助。

1 个答案:

答案 0 :(得分:0)

首先,您需要鼠标光标所指向的点。您必须实现的方法是

- (void)mouseMoved:(NSEvent *)theEvent

NSEvent有一个名为

的方法
- (NSPoint)locationInWindow
正如您可能猜到的那样,

可以让您在窗口中找到光标的位置。

现在您必须在视图中找到该位置。这是通过NSView方法

完成的
- (NSPoint)convertPoint:(NSPoint)aPoint fromView:(NSView *)aView

其中点来自locationInWindow,视图是您要在其中执行动画的视图

e.g。

CGPoint mousePoint = [[[self window] contentView] convertPoint:[theEvent locationInWindow] fromView:self];

然后您可以通过视图框架设置位置,也可以使用视图图层的position属性。