繁体   English   中英

将动画图层绘制到 NSView

[英]Drawing animated layers to an NSView

我正在尝试将多个形状绘制到 NSView。 然后我需要通过围绕它们的中心旋转这些形状来为它们设置动画。

我需要能够准确控制它们旋转的速度/方向。

到目前为止,我已经直接对 CGContext 进行了绘图(见下文),我不确定这是否是最好的方法,我愿意对此进行更正。

有人可以指出我正确的方向吗?

我应该改为将每个形状绘制到单独的 CALayer 并为其设置动画吗?

如果是这样,我将 animation 代码放在哪里? 视图控制器?

提前致谢

ps 下面的代码只是相关的绘图代码,因此不会构建,因为它缺少一些所需的 state。

class CanvasView: NSView {
        
    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        layer?.backgroundColor = CGColor.black
        
        
        if let viewModel = _viewModel {
            viewModel.layers.forEach(drawLayer)
        }
    }
    
    private func drawLayer(_ layer: CanvasViewLayerModel) {
        drawLines(layer.points)
        layer.points.forEach(drawPoint)
    }
    
    private func drawLines(_ points: [CGPoint]) {
        let context = NSGraphicsContext.current!.cgContext
        
        context.saveGState()
        
        context.setStrokeColor(CGColor.white)
        context.setLineWidth(2)
        
        context.beginPath()
        let something = points.map { CGPoint($0.x, $0.y, size: pointSize) }
        context.addLines(between: something)
        context.closePath()
        context.strokePath()
        
        context.restoreGState()
    }
        
    private func drawPoint(_ point: CGPoint) {
        let context = NSGraphicsContext.current!.cgContext
        
        context.saveGState()
        
        // Outer Ring
        context.setFillColor(CGColor.white)
        context.fillEllipse(in: NSRect(x: point.x,
                                       y: point.y,
                                       width: pointSize,
                                       height: pointSize))
        
        // Inner Background Colour
        context.setFillColor(CGColor.black)
        context.fillEllipse(in: NSRect(x: point.x + strokeSize * 0.5,
                                       y: point.y + strokeSize * 0.5,
                                       width: pointSize - strokeSize,
                                       height: pointSize - strokeSize))
        
        // Inner Dot
        context.setFillColor(CGColor.white)
        context.fillEllipse(in: NSRect(x: point.x + innerDotSize * 0.5,
                                       y: point.y + innerDotSize * 0.5,
                                       width: innerDotSize,
                                       height: innerDotSize))
        
        context.restoreGState()
    }
}

暂无
暂无

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

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