呈现不同大小的相同图像。

时间:2022-10-31 10:20:38

I have bunch of images in my assets. What I am trying to do is render the image in status bar of OSX as following:

我的资产中有很多图片。我想做的是将OSX状态栏中的图像呈现如下:

let icon = NSImage(named: "statusIcon")
icon?.size = NSSize.init(width: 18, height: 18)

icon?.template = true
statusItem.image = icon
statusItem.menu = statusMenu

and also using it in one of my view which opens:

在我打开的一个视图中也使用它:

self.dayIcon.image = NSImage(named: "statusIcon")

The problem is as soon as I set the status bar image, the image in the view also changes, i.e. both the color and the size(changes to 18x18)

问题是,一旦我设置了状态栏图像,视图中的图像也会发生变化,比如颜色和大小(更改为18x18)

I have tried using

我已经尝试使用

icon?.cacheMode = NSImageCacheMode.Never

but there is no effect.

但没有影响。

Is this how it is supposed to be? Can I not use the same image and render it differently at different places. They are both different NSImage instances.

是这样的吗?我不能在不同的地方使用相同的图像并呈现不同的效果吗?它们都是不同的实例。

2 个解决方案

#1


5  

They are both different NSImage instance.

它们都是不同的NSImage实例。

They are not, and that is, indeed, your problem.

他们不是,这确实是你的问题。

+[NSImage imageNamed:] may return an existing cached instance of the image.

+[NSImage imageNamed:]可以返回图像的现有缓存实例。

If you want to change the size on the image without affecting anyone else who may be holding a reference, make a copy of it. The copy of the NSImage is lightweight - it doesn't duplicate the underlying image representations which hold the rendering (bitmap, in the PNG case) data.

如果您想更改图像的大小而不影响其他可能持有引用的人,请复制它。NSImage的副本是轻量级的——它不会复制包含呈现(PNG案例中的位图)数据的底层图像表示。

#2


3  

I suppose that you need to resize image first. For doing that you may use different ways. For example you can write extension for NSImage class. For example Resize NSImage in Swift

我想你需要先调整图像的大小。要做到这一点,你可以用不同的方法。例如,您可以为NSImage类编写扩展。例如,在Swift中调整NSImage

#1


5  

They are both different NSImage instance.

它们都是不同的NSImage实例。

They are not, and that is, indeed, your problem.

他们不是,这确实是你的问题。

+[NSImage imageNamed:] may return an existing cached instance of the image.

+[NSImage imageNamed:]可以返回图像的现有缓存实例。

If you want to change the size on the image without affecting anyone else who may be holding a reference, make a copy of it. The copy of the NSImage is lightweight - it doesn't duplicate the underlying image representations which hold the rendering (bitmap, in the PNG case) data.

如果您想更改图像的大小而不影响其他可能持有引用的人,请复制它。NSImage的副本是轻量级的——它不会复制包含呈现(PNG案例中的位图)数据的底层图像表示。

#2


3  

I suppose that you need to resize image first. For doing that you may use different ways. For example you can write extension for NSImage class. For example Resize NSImage in Swift

我想你需要先调整图像的大小。要做到这一点,你可以用不同的方法。例如,您可以为NSImage类编写扩展。例如,在Swift中调整NSImage