5

I've studied Apple's example: CocoaDragAndDrop. I understand how to drag a image to NSImageView and drag an image between views. However, I still don't known how to drag an image and save it to a file when the image is dropped onto the Finder.

Can anybody give me a example?

phaibin
  • 379
  • 3
  • 9
  • I want to implement drag the image from NSImageView to save. Just like drag an image in safari to Finder and save it. – phaibin Oct 16 '11 at 07:15

2 Answers2

10

I finally found out how to do it. And I wrote a demo on Github

phaibin
  • 379
  • 3
  • 9
  • You are my savior. – rocky Mar 22 '16 at 19:26
  • 3
    Anyone knows how to implement source dragging (the way you see the image while dragging) in Swift and targetting 10.10? It seems the `dragImage`method has been marked unavailable and I can't figure out how to achieve the same effect – rmvz3 Mar 25 '16 at 21:26
  • 1
    @rmvz3 check out this example by Apple (I'm reading it as of now but looks promising) https://developer.apple.com/documentation/appkit/documents_files_and_icloud/supporting_drag_and_drop_through_file_promises – hyouuu Nov 10 '18 at 23:44
-2
-(IBAction)saveImageButtonPushed:(id)sender
{
    NSLog(@"saveImageButtonPushed");

    NSBitmapImageRep *rep;
    NSData *data;
    NSImage *image;

    [self lockFocus];
    rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[self frame]];
    [self unlockFocus];

    image = [[[NSImage alloc] initWithSize:[rep size]] autorelease];
    [image addRepresentation:rep];

    data = [rep representationUsingType: NSPNGFileType properties: nil];
        //save as png but failed
    [data writeToFile: @"asd.png" atomically: NO];

        //save as pdf, succeeded but with flaw
    data = [self dataWithPDFInsideRect:[self frame]];
    [data writeToFile:@"asd.pdf" atomically:YES];
}
//......
@end
Gabriel
  • 3,039
  • 6
  • 34
  • 44