0

当我移动第一个 UIImageView 的视图光标时,我使用 UIPanGestureRecognizer 输出点 rgb 的颜色。使用这种颜色,我必须在第二个 uiview 中创建一个渐变,从起始颜色的左侧开始,到白色的右侧。我注意到在计算第一个 rgb 后,第二个 UIView 的 backgroundColor 的颜色被纠正,但是在移动第一个 UIView 的光标并在 rgb 中更改颜色后,第二个 uiview 的 backgroundColor 保持不变。

在此处输入图像描述

  @objc func wasDragged(gestureRecognizer: UIPanGestureRecognizer) {

    if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {

        let translation = gestureRecognizer.translation(in: self.view)

        gestureRecognizer.view!.center = CGPoint(x: gestureRecognizer.view!.center.x + translation.x, y: gestureRecognizer.view!.center.y + translation.y)
        gestureRecognizer.setTranslation(CGPoint.zero, in: self.view)
        let color = self.imageView.getPixelColorAt(point: gestureRecognizer.view!.center)
       // color is correct

        UIView.animate(withDuration: 1, delay: 0.0, options:[.repeat, .autoreverse], animations: {
             self.gradientview.backgroundColor = UIColor.clear
             self.gradientview.gradientBackground(from: color, to:   UIColor.white, direction: GradientDirection.leftToRight)
       // color is correct only first time, after remains unchanged
        }, completion:nil)

    }
 }

在扩展中

我从这个示例开始创建渐变 以 编程方式创建具有颜色渐变的 UIView

  enum GradientDirection {
     case leftToRight
     case rightToLeft
    case topToBottom
    case bottomToTop
 }

 extension UIView {
     func gradientBackground(from color1: UIColor, to color2: UIColor, direction: GradientDirection) {
    let gradient = CAGradientLayer()
    gradient.frame = self.bounds
    gradient.colors = [color1.cgColor, color2.cgColor]

    switch direction {
    case .leftToRight:
        gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
    case .rightToLeft:
        gradient.startPoint = CGPoint(x: 1.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 0.0, y: 0.5)
    case .bottomToTop:
        gradient.startPoint = CGPoint(x: 0.5, y: 1.0)
        gradient.endPoint = CGPoint(x: 0.5, y: 0.0)
    default:
        break
    }

    self.layer.insertSublayer(gradient, at: 0)
 }
}
4

1 回答 1

0

您必须将所有子层设置为零

 self.gradientview.backgroundColor = UIColor.clear
 self.gradientview.layer.sublayers = nil

 UIView.animate(withDuration: 1, delay: 0.0, options:[.repeat, .autoreverse], animations: {

            self.gradientview.gradientBackground(from: color, to: UIColor.white, direction: GradientDirection.leftToRight)


   }, completion:nil)
于 2017-07-18T14:31:53.657 回答