动画CAShapeLayer&阴影独立

时间:2016-12-12 00:03:48

标签: ios swift3 core-animation cashapelayer caanimation

我有一个名为'HexagonView'的'UIView'子类,我在其中创建一个显示六边形的图层。然后我添加另一个与阴影层具有相同路径的图层。我不得不这样做,因为我无法在'layer.mask'形状之外显示阴影。 我的目标是为形状的360°旋转设置动画,同时阴影保持在其位置而不是随着旋转移动。

参见示例图片

Animated Hexagon

这是我到目前为止的代码:

@IBDesignable class HexagonView: UIView {

override func prepareForInterfaceBuilder()
{

    super.prepareForInterfaceBuilder()

    configureLayer()

    addShadow()

}

override init(frame: CGRect)
{

    super.init(frame: frame)

    configureLayer()

    addShadow()

}

required init?(coder aDecoder: NSCoder)
{

    super.init(coder: aDecoder)

    configureLayer()

    addShadow()

}

func configureLayer()
{

    let maskLayer = CAShapeLayer()

    maskLayer.fillRule = kCAFillRuleEvenOdd

    maskLayer.frame = bounds

    UIGraphicsBeginImageContext(frame.size)

    maskLayer.path = getHexagonPath().cgPath

    UIGraphicsEndImageContext()

    layer.addSublayer(maskLayer)

}

private func getHexagonPath() -> UIBezierPath
{

    let width = frame.size.width

    let height = frame.size.height

    let padding = width * 1 / 8 / 2

    let path = UIBezierPath()

    path.move(to: CGPoint(x: width / 2, y: 0))

    path.addLine(to: CGPoint(x: width - padding, y: height / 4))

    path.addLine(to: CGPoint(x: width - padding, y: height * 3 / 4))

    path.addLine(to: CGPoint(x: width / 2, y: height))

    path.addLine(to: CGPoint(x: padding, y: height * 3 / 4))

    path.addLine(to: CGPoint(x: padding, y: height / 4))

    path.close()

    return path

}

func addShadow()
{

    let s = CAShapeLayer()
    s.fillColor = backgroundColor?.cgColor
    s.frame = layer.bounds
    s.path = getHexagonPath().cgPath

    layer.backgroundColor = UIColor.clear.cgColor
    layer.addSublayer(s)

    layer.masksToBounds = false

    layer.shadowColor = AppAppearance.Colors.labelBackground.cgColor
    layer.shadowOffset = CGSize(width: 5, height: 10)
    layer.shadowOpacity = 0.5
    layer.shadowPath = getHexagonPath().cgPath
    layer.shadowRadius = 0

}


func rotate(duration: CFTimeInterval = 1.0, completionDelegate: AnyObject? = nil)
{

    let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
    rotateAnimation.fromValue = 0.0
    rotateAnimation.toValue = CGFloat(M_PI * 2.0)
    rotateAnimation.duration = duration
    rotateAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)


    if let delegate = completionDelegate as? CAAnimationDelegate {
        rotateAnimation.delegate = delegate
    }

    layer.add(rotateAnimation, forKey: nil)

}
}

如何在其起始位置实现阴影旋转,而不是将其连接到白色图层。

0 个答案:

没有答案