2016-09-03 15 views
2

NSImageView의 하위 클래스가 있으며 CALayer의 인스턴스가 만들어 지므로 이미지에 사각형이 표시됩니다. 질문은 마우스가 아래쪽 (마우스 포인터가 사각형 내부에있을 때)에 드래그하여이 사각형을 이동하는 방법입니다. 마우스를 올리면이 사각형 (CALayer)이 이미지의 새 위치에 있어야합니다. 예를NSImageView에서 CALayer를 이동하는 방법

class ImageViewWithRectangle: NSImageView 
{ 
    var shape : CAShapeLayer! 

    func drawRectangle() 
    { 
     shape = CAShapeLayer() 
     shape.lineWidth = 1.0 
     shape.fillColor = NSColor.clear().cgColor 
     shape.strokeColor = NSColor.gray().cgColor 
     shape.lineDashPattern = [1,1] 
     self.layer?.addSublayer(shape) 

     let path = CGMutablePath() 
     path.moveTo(nil, x: 1, y: 1) 
     path.addLineTo(nil, x: 1, y: 50) 
     path.addLineTo(nil, x: 50, y: 50) 
     path.addLineTo(nil, x: 50, y: 1) 
     path.closeSubpath() 
     self.shape.path = path 

    } 
}  
+0

나는 지금까지 해본 코드를 보여줄 것을 제안합니다. –

+0

@Jeshua Lacock 예제를 추가했습니다 – VYT

+0

마우스 이벤트는 어디에 있습니까? https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/HandlingMouseEvents/HandlingMouseEvents.html –

답변

3

를 들어

당신은 단지 마우스 이벤트를 구현, 당신의 목표에 매우 가까이있다!


class ImageViewWithRectangle: NSImageView { 

    var shape : CAShapeLayer! 

    var shapeRect = NSMakeRect(10, 10, 100, 50) 

    var shouldMove = false; 

    var anchorPoint : NSPoint! 

    override func awakeFromNib() { 

     //We MUST implement layers! Otherwise nothing will work!! 
     //You could do it even through Interface Builder 

     self.wantsLayer = true; 

    } 

    override func drawRect(dirtyRect: NSRect) { 

     //Every time the view is drawn, remove the old layer 
     self.layer?.sublayers?.forEach({ $0.removeFromSuperlayer() }) 

     //Draw the new one 
     self.drawRectangle() 
    } 

    func drawRectangle() 
    { 

     //Draw the layer 
     shape = CAShapeLayer() 
     shape.lineWidth = 1.0 
     shape.fillColor = NSColor(calibratedWhite: 1, alpha: 0).CGColor 
     shape.strokeColor = NSColor.grayColor().CGColor 
     shape.lineDashPattern = [1,1] 
     shape.backgroundColor = NSColor.greenColor().CGColor 

     //No need for CGPaths for a simple rect, just set the frame and fill it 
     shape.frame = self.shapeRect 

     self.layer?.addSublayer(shape) 

    } 

    //Implmenet mouse events 
    override func mouseDown(theEvent: NSEvent) { 

     //get coordinates 
     let pos = theEvent.locationInWindow 

     //Check if inside the rect 
     if ((pos.x >= self.shapeRect.origin.x) && (pos.x <= self.shapeRect.origin.x + self.shapeRect.size.width)) { 

      //X match, now check Y 
      if ((pos.y >= self.shapeRect.origin.y) && (pos.y <= self.shapeRect.origin.y + self.shapeRect.size.height)) { 

       //If we get here, then we're insisde the rect! 
       self.shouldMove = true; 

       //OPTIONAL : Set an anchor point 
       self.anchorPoint = NSMakePoint(pos.x - self.shapeRect.origin.x, pos.y - self.shapeRect.origin.y); 


      } 

     } 


    } 

    override func mouseDragged(theEvent: NSEvent) { 

     if (self.shouldMove) { 

      let pos = theEvent.locationInWindow 

      //Update rect origin, or whatever you want to use as anchor point 
      self.shapeRect.origin = NSMakePoint(pos.x - self.anchorPoint.x, pos.y - self.anchorPoint.y) 

      //Redraw the view 
      self.display() 

     } 

    } 

    override func mouseUp(theEvent: NSEvent) { 

     if (self.shouldMove) { 

      //Reset value 
      self.shouldMove = false; 

     } 

    } 

} 

이 출력은이 같은 것 (없음 BG 이미지하지만 설정되어 있지 않은)

: 여기

는 작업 조각입니다

Before dragging After dragging

당신은 전환 효과, 테두리, 그라데이션 및 많은 더 추가 할 수 있습니다!

CALayers와 더 일반적으로 CoreAnimation은 정말 강력합니다! 당신이 해명이 필요하면 알려 주시기 바랍니다

, 나는이 그렇게 올바른로이 답을 표시하면 다른 사람들이 사용할 수 있도록, 도움이 희망

!

건배.

+0

위대한 답변 주셔서 감사합니다! 좋은 교수법의 좋은 예입니다! – VYT

+0

도움이 되니 기쁩니다. :) –