开发者

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

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

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

I'm actually dimming icons for the sam开发者_开发知识库e 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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜