在具有位置坐标的应用程序中,在ImageView中点击时,我无法捕捉到完美的RGB颜色。我是这样写的:
extension UIImage {
func getPixelColors(atLocation location: CGPoint, withFrameSize size: CGSize) -> UIColor {
let x: CGFloat = (self.size.width) * location.x / size.width
let y: CGFloat = (self.size.height) * location.y / size.height
let pixelPoint: CGPoint = CGPoint(x: x, y: y)
let pixelData = self.cgImage!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelIndex: Int = ((Int(self.size.width) * Int(pixelPoint.y)) + Int(pixelPoint.x)) * 4
let r = CGFloat(data[pixelIndex]) / CGFloat(255.0)
let g = CGFloat(data[pixelIndex+1]) / CGFloat(255.0)
let b = CGFloat(data[pixelIndex+2]) / CGFloat(255.0)
let a = CGFloat(data[pixelIndex+3]) / CGFloat(255.0)
//let testColor = UIColor(red: r, green: g, blue: b, alpha: a)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
我叫getPixelColors:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
print("Error: touches is empty.")
return
}
let location = touch.location(in: imgTarget)
let pin = UIImageView(frame: CGRect(x: location.x - 14, y: location.y - 14, width: 30, height: 30))
pin.image = UIImage(named: "gMarker")
imgTarget.addSubview(pin)
rgb = (imgTarget.image?.getPixelColors(atLocation: location, withFrameSize: imgTarget.frame.size))! }
如果我点击图像的中央部分,则rgb代码是正确的, 我离中心越远,误差增加得越多