Image does not want to drag

I follow the 23rd chapter of Aaron Cocoa programming for Mac OS X.
I need to drag the letter from the view and copy it to another application, for example, edit the text.
This is the part of the code that I find problems with:

- (void) mouseDragged:(NSEvent *)theEvent { NSPasteboard* pb=[NSPasteboard pasteboardWithName: NSDragPboard]; NSPoint down=[mouseDownEvent locationInWindow]; NSPoint drag=[theEvent locationInWindow],p; NSSize size=[string sizeWithAttributes: attributes]; NSRect imageBounds; NSImage* image=[NSImage alloc]; float distance; distance= hypot(down.x-drag.x, down.y-drag.y); if(distance<3 || [string length]==0) return; image=[image initWithSize: size]; imageBounds.origin=NSZeroPoint; imageBounds.size=size; [image lockFocus]; [self drawStringCenteredIn: imageBounds]; [image unlockFocus]; p=[self convertPoint: down fromView: nil]; px= px - size.width/2; py= py - size.height/2; [self writeToPasteboard: pb]; [self dragImage: image at: p offset: NSZeroSize event: mouseDownEvent pasteboard: pb source: self slideBack: YES]; } 

Where:
- mouseDownEvent is an event previously saved when the user clicked on the lecturer (mouseDown event),
- string is an NSMutableAttributesString, a string with max 1 that contains the lecture that will be displayed in the view;

When an event occurs, the letter is already displayed, so the line has a length of 1). If I forget some important information, please ask.

Problem: The drag and drop operation works fine, but the problem is that while I am dragging and dropping the image, I cannot see how the image is shifting from its original position.
This is what I see when I drag the letter:

enter image description here

Here is what I should see:

enter image description here

So, the letter should be crowded out, but this does not happen. I do not understand the cause of this problem, I think the drawImageCenteredIn method should work fine. This is the code for this method:

 - (void) drawStringCenteredIn: (NSRect) rect { NSSize size=[string sizeWithAttributes: attributes]; NSPoint origin; origin.x= rect.origin.x+ (rect.size.width+size.width)/2; origin.y=rect.origin.y + (rect.size.height+size.height)/2; [string drawAtPoint: origin withAttributes: attributes]; } 
+4
source share
1 answer

It's simple. The sign in these two lines is incorrect:

  origin.x= rect.origin.x+ (rect.size.width-size.width)/2; origin.y= rect.origin.y + (rect.size.height-size.height)/2; 

Here is the corrected method:

 - (void) drawStringCenteredIn: (NSRect) rect { NSSize size=[string sizeWithAttributes: attributes]; NSPoint origin; origin.x= rect.origin.x+ (rect.size.width-size.width)/2; origin.y= rect.origin.y + (rect.size.height-size.height)/2; [string drawAtPoint: origin withAttributes: attributes]; } 
+1
source

Source: https://habr.com/ru/post/1434962/


All Articles