旋转图像-45度

时间:2016-05-01 06:10:07

标签: swift

我正在构建关于 FloatingButton 的示例。

但旋转图像有些麻烦。我希望它像这个链接一样旋转

https://github.com/yoavlt/LiquidFloatingActionButton

但我的按钮是:

enter image description here

正如您所看到的,当我第一次点击时,它运行良好:D,它变换为x,但是当我再次点击时,我希望它恢复原状,如+,但它效果不好。

这是我的代码:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var floatingButton: UIImageView!
    var floatingButtonIsActive = false

    override func viewDidLoad() {
        super.viewDidLoad()

        addShadowToFloatingButton()
        let gesture = UITapGestureRecognizer(target: self, action: #selector(floatingButtonTapped(_:)))
        floatingButton.addGestureRecognizer(gesture)
    }

    private func addShadowToFloatingButton() {
        floatingButton.layer.shadowColor = UIColor.grayColor().CGColor
        floatingButton.layer.shadowOffset = CGSize(width: -2, height: 2)
        floatingButton.layer.shadowOpacity = 1
        floatingButton.layer.shadowRadius = 1
    }

    func floatingButtonTapped(sender: UITapGestureRecognizer) {

        if floatingButtonIsActive == false {

            UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: .CurveEaseInOut, animations: {
                self.floatingButton.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4))
                }, completion: { _ in
                    self.floatingButtonIsActive = true
            })

        } else {
            UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: .CurveEaseInOut, animations: {
                self.floatingButton.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_4))
                }, completion: { _ in
                    self.floatingButtonIsActive = false
            })
        }
    }
}

2 个答案:

答案 0 :(得分:10)

完成后将转换设置为CGAffineTransformIdentity。这是它最初的转变。当您设置变换时,无论其当前角度如何,您都要告诉它旋转到的绝对角度。

func floatingButtonTapped(sender: UITapGestureRecognizer) {

    if floatingButtonIsActive == false {

        UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: .CurveEaseInOut, animations: {
            self.floatingButton.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4))
            }, completion: { _ in
                self.floatingButtonIsActive = true
        })

    } else {
        UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: .CurveEaseInOut, animations: {
            self.floatingButton.transform = CGAffineTransformIdentity
            }, completion: { _ in
                self.floatingButtonIsActive = false
        })
    }
}

答案 1 :(得分:3)

Swift 4

180"旋光度:

self.yourLayerName.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))

返回默认位置:

self.yourLayerName.transform = .identity

为了改变旋转角度,你可以乘法或除法" pi"号。

代表45"你需要在下面实现的轮换:

self.yourLayerName.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi/4))