首页 > 解决方案 > 从 PaintCode 强制自定义 NSView 重绘

问题描述

我在PaintCode中创建了一个以编程方式绘制的图标(但这个问题不一定特定于该工具),我正试图让该图标重绘。

我使用这样的自定义类:

class IconTabGeneral: NSView {
  override func draw(_ dirtyRect: NSRect) {
    StyleKitMac.drawTabGeneral()
  }
}

drawTabGeneral()StyleKitMac类中的一个方法(由 PaintCode 生成),如下所示(我将省略所有bezierPath细节):

@objc dynamic public class func drawTabGeneral(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 22, height: 22), resizing: ResizingBehavior = .aspectFit) {
  //// General Declarations
  let context = NSGraphicsContext.current!.cgContext

  //// Resize to Target Frame
  NSGraphicsContext.saveGraphicsState()
  let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 22, height: 22), target: targetFrame)
  context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
  context.scaleBy(x: resizedFrame.width / 22, y: resizedFrame.height / 22)

  //// Bezier Drawing
  let bezierPath = NSBezierPath()
  ...
  bezierPath.close()
  StyleKitMac.accentColor.setFill() ⬅️Custom color set here 
  bezierPath.fill()

  NSGraphicsContext.restoreGraphicsState()
}

accentColor定义有一个可以由用户更改的设置。在用户更改新颜色后,我无法让我的实例IconTabGeneral重绘以获取新颜色。

我试过这个没有任何运气:

iconGeneralTabInstance.needsDisplay = true

我的理解是,这needsDisplay将迫使该draw功能再次触发,但显然不是。

知道如何让这个图标重绘并重新填充它bezierPath吗?

标签: swiftnsviewnsbezierpathsetneedsdisplaypaintcode

解决方案


我想我明白了。事实证明,PaintCode 生成的StyleKitMac类正在缓存颜色。事实上,图标是在needsDisplay设置后重新绘制的。所以我只需要刷新缓存的颜色值。


推荐阅读