0
当我移动第一个UIImageView的视图光标时,使用UIPanGestureRecognizer获得点rgb的颜色输出。使用这种颜色,我必须在第二个uiview中创建一个渐变,该渐变从起始颜色的左侧开始,然后到达白色的右侧。我注意到,在计算第一个RGB后,第二个UIView的backgroundColor的颜色被校正,但是在移动第一个UIView的光标并获得RGB颜色变化后,第二个UI的backgroundColor保持不变。动态backgroundColor UIImageView不更新iOS
@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)
}
}