Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to draw an NSImage dimmed out (like a disabled view)

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).

Non-dimmedDimmed

I'm actually dimming icons for the same use-case as Xcode dimming icons like above (i.e. document has unsaved changes).

like image 819
d11wtq Avatar asked Nov 25 '10 11:11

d11wtq


2 Answers

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]

like image 182
Regexident Avatar answered Sep 30 '22 10:09

Regexident


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
}
like image 36
Robin Stewart Avatar answered Sep 30 '22 10:09

Robin Stewart