2017-07-18 1 views
0

Lorsque je déplace le curseur de la première vue UIImageView, la couleur du point rgb est générée à l'aide d'un UIPanGestureRecognizer. Avec cette couleur, je dois créer un dégradé dans la deuxième vue qui commence à gauche de la couleur de départ et qui va à droite dans le blanc. J'ai remarqué qu'après avoir calculé le premier rgb, la couleur du backgroundColor du second UIView est corrigée mais après avoir déplacé le curseur du premier UIView et obtenu des changements dans rgb, la couleur mais la backgroundColor du second Uiview reste inchangée.Dynamic backgroundColor UIImageView ne met pas à jour 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) 

    } 
} 

dans les extensions

Je crée un gradient à partir de cet exemple 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) 
} 
} 

Répondre

0

Vous devez définir à zéro tous souscouche

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)