【问题标题】:Force Custom NSView from PaintCode to Redraw从 PaintCode 强制自定义 NSView 重绘
【发布时间】:2019-11-08 19:11:23
【问题描述】:

我在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吗?

【问题讨论】:

    标签: swift nsview nsbezierpath setneedsdisplay paintcode


    【解决方案1】:

    使用NSImageView 怎么样?这是一个工作示例:

    import AppKit
    
    enum StyleKit {
      static func drawIcon(frame: CGRect) {
        let circle = NSBezierPath(ovalIn: frame.insetBy(dx: 1, dy: 1))
        NSColor.controlAccentColor.setFill()
        circle.fill()
      }
    }
    
    let iconView = NSImageView()
    iconView.image = .init(size: .init(width: 24, height: 24), flipped: true) { drawingRect in
      StyleKit.drawIcon(frame: drawingRect)
      return true
    }
    
    import PlaygroundSupport
    PlaygroundPage.current.liveView = iconView
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-09
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        • 2010-12-25
        • 2015-12-31
        • 1970-01-01
        相关资源
        最近更新 更多