NSImage大小问题

发布于 2024-11-17 20:39:43 字数 217 浏览 1 评论 0原文

我在两个不同的控制器中使用相同的图像资源。在两个控制器中,图像以不同的尺寸显示,问题是,一旦图像以比原始尺寸更小的尺寸显示,下次我通过 [NSImage imageNamed:@"resource.png"] 获取图像时 图像大小设置为最后一次使用的大小。我尝试在 NSImage 上调用 recache 方法,并尝试将缓存模式设置为任何可能的值,但它不起作用。

有什么想法吗?

I'm using the same image resource in two different controllers. In both controllers the image is shown in different sizes, the problem is that once the image is shown in a smaller size than the original, the next time I get the image by [NSImage imageNamed:@"resource.png"] the image size is set to the last size it took. I tried by invoking the recache method on NSImage and also tried to set the cache mode to any the posible value, but it didn't work.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

独行侠 2024-11-24 20:39:43

您永远不应该修改从 imageNamed: 获取的 NSImage 实例。返回的实例与其他客户端共享,因此不应更改。

如果您必须在图像上setSize:,只需制作一份副本并使用该副本即可:

NSImage *image = [[[NSImage imageNamed:@"foo.png"] copy] autorelease];
[image setSize:(NSSize){128, 128}];

You should never modify an instance of NSImage obtained from imageNamed:. The returned instance is shared with other clients, so it should not be changed.

If you have to setSize: on the image, just make a copy and use that one:

NSImage *image = [[[NSImage imageNamed:@"foo.png"] copy] autorelease];
[image setSize:(NSSize){128, 128}];
只有一腔孤勇 2024-11-24 20:39:43

问题是,

[NSImage imageNamed]

正如你提到的,它在缓存中,只要它在缓存中,它就会返回缓存的图像,所以你需要做的是首先释放以前的引用或使用对象的 setName 方法并设置为 nil。以下是文档参考:

在某些情况下,NSImage 类可能会缓存对返回图像对象的引用以提高性能。但是,该类仅在对象存在时才保留缓存的对象。如果图像对象随后被释放,或者因为它的保留计数为 0,或者因为它在垃圾收集应用程序中的任何地方都没有被引用,则该对象可能会被悄悄地从缓存中删除。因此,如果您打算保留返回的图像对象,则必须像保留任何 Cocoa 对象一样保留它。 您可以通过调用对象的 setName: 方法并传递 nil 作为图像名称来显式从缓存中清除图像对象。

The thing is that

[NSImage imageNamed]

As you mentioned is in the cache, and as long as it is in the cache it will return the cached image so what you need to do is first released the previous reference or use the object's setName method and setting to nil. Here is the documentation reference:

The NSImage class may cache a reference to the returned image object for performance in some cases. However, the class holds onto cached objects only while the object exists. If the image object is subsequently released, either because its retain count was 0 or it was not referenced anywhere in a garbage-collected application, the object may be quietly removed from the cache. Thus, if you plan to hold onto a returned image object, you must retain it like you would any Cocoa object. You can clear an image object from the cache explicitly by calling the object’s setName: method and passing nil for the image name.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文