简体   繁体   English

NSMenuItem 图像在绘制时失真

[英]NSMenuItem image is distorted when drawn

I'm building up a list of submenu items, that contain an image.我正在建立一个包含图像的子菜单项列表。 I do load an image from the bundle, then want to draw it in the menu item swatch.我确实从包中加载了一个图像,然后想在菜单项样本中绘制它。

Here's the code:这是代码:

  NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:@"Title" action:nil keyEquivalent:@""];

  [item setAction:@selector(action:)];
  [item setTarget:self];
  [item setEnabled:YES];

  NSImage *img = [[NSImage alloc] initWithSize:NSMakeSize(24, 16)];

  [img lockFocus];

  NSString *imgFile = [mainBundle pathForResource:@"swatch" ofType: @"png"];
  NSImage *swtch = [[NSImage alloc] initWithContentsOfFile:imgFile];

  NSRect imgRect;
  imgRect.origin = NSZeroPoint;
  imgRect.size = [swtch size];
  [swtch drawInRect:NSMakeRect(0, 0, 24, 16)
           fromRect:imgRect
          operation:NSCompositingOperationSourceOver
           fraction:1.0f];

  [img unlockFocus];

  [item setImage:[img copy]];

If I select the menu item from the submenu, the NSPopupButton displays the correct image.如果我从子菜单中选择 select 菜单项,则 NSPopupButton 会显示正确的图像。

弹出按钮

If I get a bitmap representation from "img", it is correct, a downsized copy of "swtch".如果我从“img”得到 bitmap 表示,那是正确的,是“swtch”的缩小副本。

But the menu item looks wrong:但是菜单项看起来不对:

菜单项图像

It only started this on Big Sur, prevoiusly all looked good.它只是在大苏尔开始的,以前一切看起来都很好。 Do I need to setup menu item or its cell different?我需要设置菜单项或其单元格不同吗?

It looks like the problem is in the image itself.看起来问题出在图像本身。 It probably has an alpha channel, but the antialiasing around the text edges was composited on a white background (hard to explain, but it can and does happen depending on how the image was made.)它可能有一个 alpha 通道,但文本边缘周围的抗锯齿是在白色背景上合成的(很难解释,但它可以而且确实会发生,具体取决于图像的制作方式。)

Does this image always draw on a white background?此图像是否始终绘制在白色背景上? If so, try re-saving the.png file without transparency.如果是这样,请尝试重新保存不透明的 .png 文件。 You can do this in Preview.app.您可以在 Preview.app 中执行此操作。 File->Export, uncheck Alpha.文件->导出,取消选中 Alpha。

If you need black antialiased text that composites properly atop any colored background, you'd need to redo the image so there's no white in it.如果您需要在任何彩色背景上正确合成的黑色抗锯齿文本,则需要重做图像,以便其中没有白色。 This can be done in Photoshop.这可以在 Photoshop 中完成。

(You might also be able to fix it by changing the blend mode to something like NSCompositingOperationDarken or NSCompositingOperationPlusDarker , but it would be cleaner to repair the image file.) (您也可以通过将混合模式更改为NSCompositingOperationDarkenNSCompositingOperationPlusDarker来修复它,但修复图像文件会更干净。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM