If I'm not really fussy about the exact tone etc of the dimmed image, is there a quick and dirty way to draw an NSImage slightly dimmed, like this? I've searched online and can't really find what I'm looking for (but I'm not very good when it comes to understanding graphics and the correct technical terms).
I'm actually dimming icons for the same use-case as Xcode dimming icons like above (i.e. document has unsaved changes).
This works fine for me:
NSImage *iconImage = [NSImage imageNamed:@"Icon"];
NSSize iconSize = [iconImage size];
NSRect iconRect = NSMakeRect(0.0, 0.0, iconSize.width, iconSize.height);
[iconImage lockFocus];
[[NSColor colorWithCalibratedWhite:0.0 alpha:0.33] set];
NSRectFillUsingOperation(iconRect, NSCompositeSourceAtop);
[iconImage unlockFocus];
[iconImage drawInRect:iconRect
fromRect:iconRect
operation:NSCompositeSourceOver
fraction:0.75];
Basically I'm adding a black layer with 33% opacity on top of the actual icon (masking it with NSCompositeSourceAtop
). And then I'm just drawing the dimmed icon with an opacity of 75%.
[Edit: got rid of temporary black image by using NSRectFillUsingOperation(...), as advised by Nikolai Ruhe]
Swift 5 function to create a dimmed version of any input image:
func dimmedImage(_ image: NSImage, alpha: CGFloat) -> NSImage {
let newImage = NSImage(size: image.size)
newImage.lockFocus()
let imageRect = NSRect(origin: .zero, size: image.size)
image.draw(in: imageRect, from: imageRect, operation: .sourceOver, fraction: alpha)
newImage.unlockFocus()
return newImage
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With