// // ImageDragView.m // ImageDrag // // Created by Joshua Pennington on 5/14/07. // #import "ImageDragView.h" @implementation ImageDragView - (void)dealloc { [self setImage:nil]; [super dealloc]; } - (void)awakeFromNib { [self setImage:[NSImage imageNamed:@"testImage"]]; } - (IBAction)resetImagePosition:(id)sender { [self setImagePosition:NSZeroPoint]; } - (void)drawRect:(NSRect)rect { // Draw background [[NSColor whiteColor] set]; NSRectFill(rect); // Draw the image NSRect destRect = {[self imagePosition], [[self image] size]}; [[self image] drawInRect:destRect fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0]; // Draw border [[NSColor grayColor] set]; NSFrameRect(rect); } - (void)mouseDown:(NSEvent *)theEvent { // We don't really care if the user clicks if there is no image. if (![self image]) return; // Convert the click's window-location to this view's coordinate system NSPoint clickLocation = [self convertPoint:[theEvent locationInWindow] fromView:nil]; // If the mousedown is "on" the image, we want to signal that its okay to drag the image. if (NSPointInRect(clickLocation, (NSRect){[self imagePosition], [[self image] size]})) [self setIsDragging:YES]; } - (void)mouseUp:(NSEvent *)theEvent { [self setIsDragging:NO]; } - (void)mouseDragged:(NSEvent *)theEvent { if (![self image]) return; // If the mousedown was not "on" the image, we don't care about the dragging the user does. if (![self isDragging]) return; // Calculate the new "image position" using the delta offset values from the event. NSPoint newOrigin = [self imagePosition]; newOrigin.x += [theEvent deltaX]; newOrigin.y -= [theEvent deltaY]; // If any portion of the new image rect is outside of the view, adjust the new imagePosition so the image rect will not be outside the frame rect. NSRect imageRect = {[self convertPoint:newOrigin toView:nil], [[self image] size]}; if (NSMaxX(imageRect) > NSMaxX([self frame])) newOrigin.x -= (NSMaxX(imageRect) - NSMaxX([self frame])); if (NSMaxY(imageRect) > NSMaxY([self frame])) newOrigin.y -= (NSMaxY(imageRect) - NSMaxY([self frame])); if (NSMinX(imageRect) < NSMinX([self frame])) newOrigin.x += NSMinX([self frame]) - NSMinX(imageRect); if (NSMinY(imageRect) < NSMinY([self frame])) newOrigin.y += NSMinY([self frame]) - NSMinY(imageRect); [self setImagePosition:newOrigin]; } - (void)setImage:(NSImage *)newImage { if (newImage != image) { [image autorelease]; image = [newImage copy]; } } - (NSImage *)image { return [[image retain] autorelease]; } - (void)setImagePosition:(NSPoint)aPoint { // If the image "moved" we need to redraw the view to display the change. if (!NSEqualPoints(imagePosition, aPoint)) [self setNeedsDisplay:YES]; imagePosition = aPoint; } - (NSPoint)imagePosition { return imagePosition; } - (void)setIsDragging:(BOOL)flag { isDragging = flag; } - (BOOL)isDragging { return isDragging; } @end