我想实现一个简单的程序,使用UIPanGestureRecognizer显示手指在图像上的点的颜色。但是,从gesture.location(in :)函数返回的CGPoint的x和y值大于预期值,因此图像中选定的颜色不正确。
例如,imageView.frame.size.width打印为375.但是当您拖动到屏幕右侧时,平移手势的x位置的最大返回值为413。
为什么返回的CGPoint的x和y值大于UIImageView的边界?
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var squareView: UIView!
var imgheight: CGFloat!
var imgwidth: CGFloat!
var heightDif: CGFloat!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
squareView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
squareView.backgroundColor = getPixelColor(pos: CGPoint(x: 50, y: 50))
view.addSubview(squareView)
imgheight = imageView.image?.size.height
imgwidth = imageView.image?.size.width
heightDif = (imageView.frame.size.height - imgheight)/2
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(recognizer:)))
imageView.addGestureRecognizer(panGesture)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getPixelColor(pos: CGPoint) -> UIColor {
let pixelData = imageView.image?.cgImage!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelInfo: Int = ((Int(imageView.image!.size.width) * Int(pos.y)) + Int(pos.x)) * 4
let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
@objc func handlePan(recognizer: UIPanGestureRecognizer) {
var point = recognizer.location(in: self.imageView)
point.y -= heightDif
if point.x >= 0 && point.y >= 0 {
squareView.backgroundColor = getPixelColor(pos: point)
}
}
}
感谢您的帮助!
答案 0 :(得分:0)
我通过以编程方式创建imageView而不是使用故事板来修复此问题。这让我可以精确控制imageView的参数,识别器。位置函数返回了预期的结果。
var imageView: UIImageView!
然后,我在viewDidLoad()中声明了它的界限:
frame = CGRect(x: 0, y: 0, width: image.size.wdith, height: image.size.height)
imageView = UIImageView(frame: frame)
view.addSubview(imageView)
其余的代码是一样的,一切正常!