簡體   English   中英

如何在可可中轉換 NSImageView?

[英]How to transform an NSImageView in cocoa?

我正在為可可苦苦掙扎。 我正在嘗試將這段動畫從 iOS 寫入可可。 想法是稍微減小 NSImageView 的大小,在動畫完成后,再次將其增加到原始大小。 這樣看起來好像按鈕(圖片)被按下了。

@IBOutlet weak var vpnButton: NSImageView!

@objc func vpnButtonPressed(pressedGestureRecognizer: UILongPressGestureRecognizer) {
        UserDefaults.standard.set(true, forKey: Constants.vpnButtonTapped)
        if (pressedGestureRecognizer.state == .began) {
            UIView.animate(withDuration: 0.15, animations: {() -> Void in
                self.vpnButton?.transform = CGAffineTransform(scaleX: 0.965, y: 0.965)})
        } else if (pressedGestureRecognizer.state == .ended) {
            UIView.animate(withDuration: 0.15, animations: {() -> Void in
                self.vpnButton.isHighlighted = !self.vpnButton.isHighlighted
                self.vpnButton?.transform = CGAffineTransform(scaleX: 1, y: 1)})
        }
    }

在可可中,我能夠找到 clickGesture。 我不確定這是否是最佳選擇。

所以我想出了這個:

@objc func vpnButtonPressed(clickedGestureRecognizer: NSGestureRecognizer) {
        UserDefaults.standard.set(true, forKey: Constants.vpnButtonTapped)
        print("clicked")
        NSAnimationContext.runAnimationGroup({_ in
            //Indicate the duration of the animation
            NSAnimationContext.current.duration = 0.5
            var transform = CGAffineTransform(scaleX: 0.965, y: 0.965)
            self.vpnButton.layer?.setAffineTransform(transform)
        }, completionHandler:{
//            var transform = self.vpnButton.layer?.affineTransform()
//            transform = CGAffineTransform(scaleX: 1, y: 1)
//            self.vpnButton.layer?.setAffineTransform(transform!)
            print("Animation completed")
        })
    }

通過將圖像稍微移到一邊,這僅起作用一次,但它不會使它變小。 如果我取消注釋完成處理程序中的三行,我也看不到動畫將其移回。

據我了解,您需要類似以下內容(如果需要,發送動作本身超出范圍 - 這里只是動畫)

Cocoa 自定義 NSImageView 點擊動畫

class MyImageView: NSImageView {

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        self.wantsLayer = true
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        self.wantsLayer = true
    }

    override func mouseDown(with event: NSEvent) {
        NSAnimationContext.runAnimationGroup({ (context) in
          context.duration = 0.15
          self.layer?.setAffineTransform(CGAffineTransform(scaleX: 0.965, y: 0.965))
        })
    }

    override func mouseUp(with event: NSEvent) {
        NSAnimationContext.runAnimationGroup({ (context) in
          context.duration = 0.15
          self.layer?.setAffineTransform(.identity)
        })
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM