Skip to content

Instantly share code, notes, and snippets.

@hekt
Created November 17, 2014 13:34
Show Gist options
  • Save hekt/9a650129db6d8cb958a0 to your computer and use it in GitHub Desktop.
Save hekt/9a650129db6d8cb958a0 to your computer and use it in GitHub Desktop.
MAC OS X COCOA プログラミング 23章で dragImage が使われているところ を beginDraggingSessionWithItems で書く
@interface BigLetterView : NSView <NSDraggingSource> {
NSColor *bgColor;
NSString *string;
NSMutableDictionary *attributes;
NSEvent *mouseDownEvent;
}
- (void)mouseDragged:(NSEvent *)event {
NSPoint down = [mouseDownEvent locationInWindow];
NSPoint drag = [event locationInWindow];
float distance = hypot(down.x - drag.x, down.y - drag.y);
if (distance < 3) {
return;
}
if ([string length] == 0) {
return;
}
NSSize s = [string sizeWithAttributes:attributes];
NSImage *anImage = [[NSImage alloc] initWithSize:s];
NSRect imageBounds;
imageBounds.origin = NSZeroPoint;
imageBounds.size = s;
[anImage lockFocus];
[self drawStringCenteredIn:imageBounds];
[anImage unlockFocus];
NSPoint p = [self convertPoint:down fromView:nil];
p.x = p.x - s.width / 2;
p.y = p.y - s.height / 2;
NSDraggingItem *dragItem = [[NSDraggingItem alloc] initWithPasteboardWriter:string];
[dragItem setDraggingFrame:NSMakeRect(p.x, p.y, s.width, s.height) contents:anImage];
NSDraggingSession *draggingSession = [self beginDraggingSessionWithItems:[NSArray arrayWithObject:dragItem] event:mouseDownEvent source:self];
draggingSession.animatesToStartingPositionsOnCancelOrFail = YES;
draggingSession.draggingFormation = NSDraggingFormationNone;
}
- (NSDragOperation)draggingSession:(NSDraggingSession *)session sourceOperationMaskForDraggingContext:(NSDraggingContext)context {
return NSDragOperationCopy | NSDragOperationDelete;
}
- (void)draggingSession:(NSDraggingSession *)session endedAtPoint:(NSPoint)screenPoint operation:(NSDragOperation)operation {
switch (operation) {
case NSDragOperationDelete:
[self setString:@""];
break;
default:
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment