开发者

I can't draw a NSRect based on where the user clicks

I am trying to draw a rectangle and let the user create it based on where he clicks and where he drags the mouse.

The code I am using to draw the NSRect is:

CGFloat width = endPoint.x-startPoint.x; //Width of rectangle.
CGFloat height = endPoint.y-startPoint.y; //Height of rectangle.
CGFloat rectXPoint = startPoint.x; //x component of corner of rect
CGFloat rectYPoint = startPoint.x; //y component of corner of rect
if (width < 0) { //Handle negavive rect size here.
    width = startPoint.x-endPoint.x;
    rectXPoint = endPoint.x;
}
if (height < 0) { //and here.
    height = startPoint.y-endPoint.y;
    rectYPoint = endPoint.y;
}
NSRect theRect = NSMakeRect(rectXPoint, rectYPoint, width, height);
[[NSColor blackColor] set];
NSRectFill(theRect);

So I can sort of get the code to work but not exactly. Sometimes it offsets the y of the rectangle from the cursor by some seemingly arbitrary amount (even though I know it isn't arbitrary). It is hard to get a screen shot considering that would involve me moving the mouse from the point it would need to be to demonstrate the point. Just in case you need to see the code for how I am getting the location of the mouse here it is:

- (void)mouseDown:(NSEvent *)event {
    NSPoint location = [self convertPointFromBase:[event locationInWindow]];
    startPoint = location;
}

- (void)mouseDragged:(NSEvent *)event {
    NSPoint location = [self convertPointFromBase:[event locationInWindow]];
    endPoint = location;
    [self setNeedsDisplay:YES];
}

And isFlipped returns YES.

I开发者_StackOverflow中文版f you need any more clarification ask what you need clarification.


Probably this line:

CGFloat rectYPoint = startPoint.x; //y component of corner of rect
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜