在ARSCNView中获取像素颜色的一种解决方法是使用hitTest(_:options:)
方法来获取点击的场景节点,并通过hitTestResult
的textureCoordinates
属性来获取对应的纹理坐标。然后,可以使用CVPixelBuffer
和CVPixelBufferGetBaseAddress
函数来获取像素数据,并使用UnsafeMutablePointer
读取像素颜色。
下面是一个示例代码:
import ARKit
extension ARSCNView {
func getPixelColor(at point: CGPoint) -> UIColor? {
guard let frame = self.session.currentFrame else {
return nil
}
let hitTestOptions: [SCNHitTestOption : Any] = [.boundingBoxOnly: true, .firstFoundOnly: true]
let hitTestResults = self.hitTest(point, options: hitTestOptions)
if let hitTestResult = hitTestResults.first {
let textureCoordinates = hitTestResult.textureCoordinates(withMappingChannel: 0)
let width = frame.capturedImage.width
let height = frame.capturedImage.height
let x = Int(textureCoordinates.x * CGFloat(width))
let y = Int(textureCoordinates.y * CGFloat(height))
if let pixelBuffer = frame.capturedImage {
CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly)
let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer)
let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
let buffer = baseAddress?.assumingMemoryBound(to: UInt8.self)
let pixel = buffer! + y * bytesPerRow + x * 4
let red = CGFloat(pixel[0]) / 255.0
let green = CGFloat(pixel[1]) / 255.0
let blue = CGFloat(pixel[2]) / 255.0
let alpha = CGFloat(pixel[3]) / 255.0
CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly)
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
}
return nil
}
}
然后,你可以使用以下方式来调用该方法:
let pixelColor = arscnView.getPixelColor(at: CGPoint(x: 100, y: 100))
上述代码中的CGPoint(x: 100, y: 100)是屏幕上的一个点,表示要获取该点处的像素颜色。你可以根据需要更改该值。