2017-07-18 1 views
0

最初のUIImageViewのビューカーソルを移動すると、UIPanGestureRecognizerを使用して、ポイントrgbの色が出力されます。この色では、開始色の左側から始まり、右側に来る2番目のuiviewにグラデーションを作成する必要があります。最初のrgbを計算した後、2番目のUIViewのbackgroundColorの色は修正されていますが、最初のUIViewのカーソルを移動してrgbの変更を取得した後に、2番目のUIのbackgroundColorは変わりません。拡張子でDynamic backgroundColor UIImageViewはiOSを更新しません

enter image description here

@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) 

    } 
} 

私はこの例から始まるグラデーションを作成 Programmatically create a UIView with color gradient

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) 
} 
} 

答えて

0

あなたがに設定する必要があり、すべてのサブレイヤはnil

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) 
関連する問題