gpt4 book ai didi

cocoa - 旋转 NSImageView 的中心使其旋转

转载 作者:行者123 更新时间:2023-12-03 16:50:02 24 4
gpt4 key购买 nike

Swift 4、macOS 10.13

我已经阅读了有关 SO 的各种答案,但仍然无法让 NSImageView 在其中心而不是其角落之一旋转。

现在,图像如下所示(视频):http://d.pr/v/kwiuwS

这是我的代码:

//`loader` is an NSImageView on my storyboard positioned with auto layout

loader.wantsLayer = true

let oldFrame = loader.layer?.frame
loader.layer?.anchorPoint = CGPoint(x: 0.5, y: 0.5)
loader.layer?.position = CGPoint(x: 0.5, y: 0.5)
loader.layer?.frame = oldFrame!

let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(-1 * .pi * 2.0)
rotateAnimation.duration = 2
rotateAnimation.repeatCount = .infinity

loader.layer?.add(rotateAnimation, forKey: nil)

我还缺少什么想法吗?

最佳答案

我刚刚创建了一个简单的演示,其中包含适用于所有 View 的方便的 setAnchorPoint 扩展。

您看到从角落旋转的主要原因是您的 anchor 以某种方式重置为 0,0。

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

@IBOutlet weak var window: NSWindow!
var imageView: NSImageView!

func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application

// Create red NSImageView
imageView = NSImageView(frame: NSRect(x: 100, y: 100, width: 100, height: 100))
imageView.wantsLayer = true
imageView.layer?.backgroundColor = NSColor.red.cgColor

window.contentView?.addSubview(imageView)
}

func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}

func applicationDidBecomeActive(_ notification: Notification) {
// Before animate, reset the anchor point
imageView.setAnchorPoint(anchorPoint: CGPoint(x: 0.5, y: 0.5))
// Start animation
if imageView.layer?.animationKeys()?.count == 0 || imageView.layer?.animationKeys() == nil {
let rotate = CABasicAnimation(keyPath: "transform.rotation")
rotate.fromValue = 0
rotate.toValue = CGFloat(-1 * .pi * 2.0)
rotate.duration = 2
rotate.repeatCount = Float.infinity

imageView.layer?.add(rotate, forKey: "rotation")
}
}
}

extension NSView {
func setAnchorPoint(anchorPoint:CGPoint) {
if let layer = self.layer {
var newPoint = NSPoint(x: self.bounds.size.width * anchorPoint.x, y: self.bounds.size.height * anchorPoint.y)
var oldPoint = NSPoint(x: self.bounds.size.width * layer.anchorPoint.x, y: self.bounds.size.height * layer.anchorPoint.y)

newPoint = newPoint.applying(layer.affineTransform())
oldPoint = oldPoint.applying(layer.affineTransform())

var position = layer.position

position.x -= oldPoint.x
position.x += newPoint.x

position.y -= oldPoint.y
position.y += newPoint.y


layer.anchorPoint = anchorPoint
layer.position = position
}
}
}

enter image description here

关于cocoa - 旋转 NSImageView 的中心使其旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46871076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com