Drawing selection box (rubberbanding, marching ants) in Cocoa, ObjectiveC

后端 未结 4 1138
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 07:28

I\'ve currently implemented a simple selection box using mouse events and redrawing a rectangle on mouse drag. Here\'s my code:

-(void)drawRect:(NSRect)dirty         


        
4条回答
  •  遥遥无期
    2020-12-13 08:14

    swift 3 version:

    import Cocoa
    import QuartzCore
    
    class myView: NSView {
    
        //MARK:Properties
        var startPoint : NSPoint!
        var shapeLayer : CAShapeLayer!
    
        override func draw(_ dirtyRect: NSRect) {
            super.draw(dirtyRect)
    
            // Drawing code here.
        }
    
    
        override func mouseDown(with event: NSEvent) {
    
            self.startPoint = self.convert(event.locationInWindow, from: nil)
    
            shapeLayer = CAShapeLayer()
            shapeLayer.lineWidth = 1.0
            shapeLayer.fillColor = NSColor.clear.cgColor
            shapeLayer.strokeColor = NSColor.black.cgColor
            shapeLayer.lineDashPattern = [10,5]
            self.layer?.addSublayer(shapeLayer)
    
            var dashAnimation = CABasicAnimation()
            dashAnimation = CABasicAnimation(keyPath: "lineDashPhase")
            dashAnimation.duration = 0.75
            dashAnimation.fromValue = 0.0
            dashAnimation.toValue = 15.0
            dashAnimation.repeatCount = .infinity
            shapeLayer.add(dashAnimation, forKey: "linePhase")
    
    
    
    
        }
    
        override func mouseDragged(with event: NSEvent) {
    
            let point : NSPoint = self.convert(event.locationInWindow, from: nil)
            let path = CGMutablePath()
            path.move(to: self.startPoint)
            path.addLine(to: NSPoint(x: self.startPoint.x, y: point.y))
            path.addLine(to: point)
            path.addLine(to: NSPoint(x:point.x,y:self.startPoint.y))
            path.closeSubpath()
            self.shapeLayer.path = path
        }
    
        override func mouseUp(with event: NSEvent) {
            self.shapeLayer.removeFromSuperlayer()
            self.shapeLayer = nil
        }
    
    
    }
    

提交回复
热议问题