开发者

How to put a custom view into an NSImageWell?

I have made what I thought was a perfect start to an image editor. It draws a square wherever you click. My problem is that when you click in a different place, or drag the mouse,开发者_运维问答 it just moves the square (instead of drawing another one). How can I draw in a custom view without "dragging" it's current contents everywhere?

Here is my code:

Header (.h)

NSBezierPath *thePath;
NSColor *theColor;
NSTimer *updateTimer;
NSPoint *mousePoint;
int testInt = 1;
int x = 0;
int y = 0;

@interface test : NSView {
    IBOutlet NSView *myView;
    IBOutlet NSButton *button;

}

@property (readwrite) NSPoint mousePoint;

@end

.m file (whatever it is called)

@implementation test

@synthesize mousePoint;

- (void) mouseDown:(NSEvent*)someEvent {         
    mousePoint = [someEvent locationInWindow];
    NSLog(@"Location: x= %f, y = %f", (float)mousePoint.x, (float)mousePoint.y);
    x = mousePoint.x;
    y = mousePoint.y;
    [button setHidden:TRUE];
    [button setHidden:FALSE];
    [self setNeedsDisplay:YES];

} 

- (void) mouseDragged:(NSEvent *)someEvent {
    mousePoint = [someEvent locationInWindow];
    NSLog(@"Location: x= %f, y = %f", (float)mousePoint.x, (float)mousePoint.y);
    x = mousePoint.x;
    y = mousePoint.y;
    [button setHidden:TRUE];
    [button setHidden:FALSE];
    [self setNeedsDisplay:YES];

}

- (void) drawRect:(NSRect)rect; {
    thePath = [NSBezierPath bezierPathWithRect:NSMakeRect(x, y, 10, 10)];
    theColor = [NSColor blackColor];
    [theColor set];
    [thePath fill];

}

@end

Why doesn't this work?


It moves your current rectangle around, because that's the only rectangle there is. If you want to draw multiple rectangles and have them persist, you need to store the NSBezierPath objects that represent the rectangles somewhere (I would suggest an NSArray) and then iterate through the array and draw each one.

Looking at your current code, you should implement mouseUp: and store an NSBezierPath object with your x and y coordinates in an NSArray. Then in drawRect: just loop through the array of NSBezierPath objects and draw each one.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜