When I move the view cursor of first UIImageView, I get output the color of the point rgb using a UIPanGestureRecognizer. With this color I have to create a gradient in the second uiview that starts from the left of the starting color and comes to the right to the white. I noticed that after calculating the first rgb the color of the backgroundColor of second UIView is corrected but after moving the cursor of the first UIView and getting changes in rgb the color but the backgroundColor of second uiview remains unchanged.
@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)
}
}
In extensions
I create gradient starting from this example 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)
}
}
You have to set to nil all sublayer
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)