NSImage transparency

喜欢而已 提交于 2019-12-08 04:12:41

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/2866532/nsimage-transparency

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!