1

I'm trying to set a custom drag icon for use in an NSTableView. Everything seems to work but I've run into a problem due to my inexperience with Quartz.

- (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent *)dragEvent offset:(NSPointPointer)dragImageOffset
{
 NSImage *dragImage = [NSImage imageNamed:@"icon.png"];
 NSString *count = [NSString stringWithFormat:@"%d", [dragRows count]];

 [dragImage lockFocus]; 
 [dragImage compositeToPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:0.5];
 [count drawAtPoint:NSZeroPoint withAttributes:nil];

 [dragImage unlockFocus];
 return dragImage;
}

Essentially what I'm looking to do is render my icon.png file with 50% opacity along with an NSString which shows the number of rows currently being dragged. The issue I'm seeing is that my NSString renders with a low opacity, but not my icon.

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
ndg
  • 2,585
  • 2
  • 33
  • 58

1 Answers1

3

The issue is that you’re drawing your icon on top of itself. What you probably want is something like this:

- (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent *)dragEvent offset:(NSPointPointer)dragImageOffset
{
 NSImage *icon = [NSImage imageNamed:@"icon.png"];
 NSString *count = [NSString stringWithFormat:@"%lu", [dragRows count]];

 NSImage *dragImage = [[[NSImage alloc] initWithSize:[icon size]] autorelease];

 [dragImage lockFocus]; 
 [icon drawAtPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:0.5];
 [count drawAtPoint:NSZeroPoint withAttributes:nil];

 [dragImage unlockFocus];
 return dragImage;
}
Wevah
  • 28,182
  • 7
  • 83
  • 72
  • That makes more sense. Thanks you. – ndg May 20 '10 at 11:29
  • 4
    Also, [`compositeToPoint:fromRect:operation:fraction:` is deprecated](http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ApplicationKit/Classes/NSImage_Class/DeprecationAppendix/AppendixADeprecatedAPI.html#//apple_ref/occ/instm/NSImage/compositeToPoint:fromRect:operation:fraction:). Use `drawAtPoint:fromRect:operation:fraction:` instead. – Peter Hosey May 21 '10 at 10:10
  • Good catch; I’d blanked that out. – Wevah May 21 '10 at 13:29