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

后端 未结 4 1112
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  -上瘾入骨i
    2020-12-13 08:28

    If anybody needs a Swift 2.0 version, here it is:

    import Cocoa
    import QuartzCore
    
    
    class myView: NSView {
    
    var startPoint : NSPoint!
    var shapeLayer : CAShapeLayer!
    
    
    
    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)
    
        // Drawing code here.
    }
    
    
    override func mouseDown(theEvent: NSEvent) {
    
        self.startPoint = self.convertPoint(theEvent.locationInWindow, fromView: nil)
    
        shapeLayer = CAShapeLayer()
        shapeLayer.lineWidth = 1.0
        shapeLayer.fillColor = NSColor.clearColor().CGColor
        shapeLayer.strokeColor = NSColor.blackColor().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.addAnimation(dashAnimation, forKey: "linePhase")
    
    
    
    
    }
    
    override func mouseDragged(theEvent: NSEvent) {
    
        let point : NSPoint = self.convertPoint(theEvent.locationInWindow, fromView: nil)
        let path = CGPathCreateMutable()
        CGPathMoveToPoint(path, nil, self.startPoint.x, self.startPoint.y)
        CGPathAddLineToPoint(path, nil, self.startPoint.x, point.y)
        CGPathAddLineToPoint(path, nil, point.x, point.y)
        CGPathAddLineToPoint(path, nil, point.x, self.startPoint.y)
        CGPathCloseSubpath(path)
        self.shapeLayer.path = path
    }
    
    override func mouseUp(theEvent: NSEvent) {
        self.shapeLayer.removeFromSuperlayer()
        self.shapeLayer = nil
    }
    
    
    
    }
    

提交回复
热议问题