Cocoa NSView Drag and Drop source tutorial

73: Produce an NSView source for Drag and Drop operations

Problem: We have an image that is displayed inside an NSView and want to make that image draggable so it can be used in a Drag and Drop operation.

Drag an image from an NSView source

Example of draging an image from an NSView source


Answer: We use Apple's NSView's dragImage:at:offset: etc. method.

Source code: we define but one class: a subclass of NSView.

// MyNSView.h #import <Cocoa/Cocoa.h> @interface MyNSView : NSView { NSImage * nsImageObj; } @property (assign) NSImage * nsImageObj; @end // MyNSView.m #import "MyNSView.h" @implementation MyNSView @synthesize nsImageObj; - (id)initWithFrame:(NSRect)frame { if (! (self = [super initWithFrame:frame] )) { NSLog(@"Error MyNSView initWithFrame"); return self; } // end if NSString * zStrFileNamePath = @"../../../shipquay-street-derry.jpg"; self.nsImageObj = [[NSImage alloc] initWithContentsOfFile:zStrFileNamePath]; [self setNeedsDisplay:YES]; return self; } // end initWithFrame -(void)mouseDown:(NSEvent *)pTheEvent { NSPoint tvarMouseInWindow = [pTheEvent locationInWindow]; NSPoint tvarMouseInView = [self convertPoint:tvarMouseInWindow fromView:nil]; NSSize zDragOffset = NSMakeSize(0.0, 0.0); NSPasteboard *zPasteBoard; zPasteBoard = [NSPasteboard pasteboardWithName:NSDragPboard]; [zPasteBoard declareTypes:[NSArray arrayWithObject:NSTIFFPboardType] owner:self]; [zPasteBoard setData:[self.nsImageObj TIFFRepresentation] forType:NSTIFFPboardType]; [self dragImage:self.nsImageObj at:tvarMouseInView offset:zDragOffset event:pTheEvent pasteboard:zPasteBoard source:self slideBack:YES]; return; } // end mouseDown //-(void)mouseDragged:(NSEvent *)pTheEvent { // [self setNeedsDisplay:YES]; //} // end mouseDragged - (void)drawRect:(NSRect)dirtyRect { [self.nsImageObj drawInRect: dirtyRect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0]; } // end drawRect @end

Example source code



Please send me your comments

If you include your e-mail I may reply!  

Page last modified: 18:58 Sunday 12th. May 2013

Julius Guzy

Paintings & Drawings

  • Link to painting of Star of Bethlehem flowers

animatedPaint