0

我试图拖动 a CGRect,但没有任何反应。矩形保持在同一个地方。这是我的mouseDragged:代码:

-(void)mouseDragged:(NSEvent *)theEvent{

NSPoint eventLocation = [theEvent locationInWindow];
NSPoint location = [self convertPoint:eventLocation fromView:self];

int locationX = location.x;
int locationY = location.y;

[self setNeedsDisplay:TRUE];

if(CGRectContainsPoint(myRect, location)){

myRect.origin.x = locationX;
myRect.origin.y = locationY;
}
}

此代码位于NSView. 我画了myRect矩形drawRect

这是我的drawRect:

- (void)drawRect:(NSRect)rect
{

int width = self.bounds.size.width;
int height = self.bounds.size.height;

myRect = CGRectMake((width/2)-50, (height /2)-50, 100, 100);


CGContextRef myContext = [[NSGraphicsContext currentContext] graphicsPort];
CGContextSetRGBFillColor(myContext, 1, 0, 0, 1);
CGContextFillRect(myContext, myRect);

 NSLog(@"drawRect: called");

}

有任何想法吗?

4

1 回答 1

2

您总是myRectdrawRect:. 似乎您想要的是根本不设置myRectdrawRect:以其当前值绘制它。所以是这样的:

- (void)drawRect:(NSRect)rect
{
    CGContextRef myContext = [[NSGraphicsContext currentContext] graphicsPort];
    CGContextSetRGBFillColor(myContext, 1, 0, 0, 1);
    CGContextFillRect(myContext, myRect);

    NSLog(@"drawRect: called");
}
于 2013-08-04T21:03:09.963 回答