2012-09-18 83 views
4

我正在按照Aaron的Cocoa編程的第二十三章Mac OS X.
我必須從視圖中拖動一個字母並將其複製到另一個應用程序中,如文本編輯。
這是我找到問題的代碼部分:圖片並不想拖拽

- (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]; 
    p.x= p.x - size.width/2; 
    p.y= p.y - size.height/2; 
    [self writeToPasteboard: pb]; 
    [self dragImage: image at: p offset: NSZeroSize event: mouseDownEvent pasteboard: pb source: self slideBack: YES]; 
} 

其中:
- mouseDownEvent是以前保存的,當用戶點擊了萊克特(mouseDown事件)的事件;
- 字符串是一個NSMutableAttributesString,是一個包含要顯示在視圖中的lecter的最大1的字符串;

當事件發生時,視圖上已顯示一個字母(所以字符串長度爲1)。如果我忘記了一些重要信息,請詢問。

問題:拖放操作可以正常工作,但問題是,當我拖動圖像時,看不到圖像從原始位置移動。
這是我所看到的,而我拖累了一封信:

enter image description here

這是我應該看到,而不是:

enter image description here

所以信宜取代,但這並不發生。我不認識這個問題的原因,我認爲drawImageCenteredIn方法應該可以正常工作。這是此方法的代碼:

- (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

很簡單。符號是在不正確這兩行:

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

這裏是校正方法:

- (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]; 
}