首页 > 解决方案 > 如何在 Swift 中对 UIImage 进行动画处理

问题描述

我在网上搜索过,但没有什么能回答我的问题。

我正在尝试将 UIImageview 设置为屏幕外的动画,将其 alpha 设置为 0,重置其位置并将 alpha 再次重置为 1。我似乎无法找到为图像设置动画的正确位置。

我已经设置了一个手势识别器来拖动图像,当图像的中心高于某个点时,我想将其动画到屏幕外。

这是 Regocnizercode :

@objc func imageDragged(gestureRecognizer: UIPanGestureRecognizer){

    //Current Point where the label is dragged
    let draggedLabelPoint = gestureRecognizer.translation(in: view)
    //Updating the center of the label : viewcenter +/- currentpoint
    matchImageView.center = CGPoint(x: view.bounds.width/2 + draggedLabelPoint.x, y: view.bounds.height/2 + draggedLabelPoint.y)

    let xFromCenter = view.bounds.width/2 - matchImageView.center.x
    var rotation = CGAffineTransform(rotationAngle: xFromCenter / -500)
    let scale = min(100/abs(xFromCenter),1)
    var scaledAndRotated = rotation.scaledBy(x: scale, y: scale)

    //Transforming the Item respective to the distance from center
    matchImageView.transform = scaledAndRotated

    if gestureRecognizer.state == .ended {
        if matchImageView.center.x < (view.bounds.width/2 - 100) {
            animateImageToSide(target: CGPoint(x: view.bounds.width - 200, y: matchImageView.center.y))
            matchImageView.alpha = 0
        }

        if matchImageView.center.x > (view.bounds.width/2 + 100) {
            animateImageToSide(target: CGPoint(x: view.bounds.width + 200, y: matchImageView.center.y))
            matchImageView.alpha = 0
        }

        //Reset the scaling variables and recentering the Item after swipe
        rotation = CGAffineTransform(rotationAngle: 0)
        scaledAndRotated = rotation.scaledBy(x: 1, y: 1)
        matchImageView.transform = scaledAndRotated
        matchImageView.center = CGPoint(x: view.bounds.width/2, y: view.bounds.height/2)

    }
}

如果重置部分与您无关,我很抱歉,但我不确定这是否会导致这种行为。

这是我目前的动画方法:

func animateImageToSide(target:CGPoint){
    UIImageView.animate(withDuration: 0.5, delay: 0, options: .curveLinear, animations: {self.matchImageView.center = target}) { (success: Bool) in
        self.updateImage()
        self.fadeInImage()//This is where i set the alpha back to 1
    }
}

我不确定是否需要使用 CGPoint。

图像的当前行为非常奇怪。大多数情况下,它会捕捉到特定位置,而不管目标位置如何。也许我对此的尝试是完全错误的。

谢谢你的帮助 !

标签: animationuiimagexcode10swift4.2

解决方案


推荐阅读