swift - 在 SKScene swift 中获取点的颜色

标签 swift sprite-kit swift3 uicolor cgpoint

我需要在 Swift 中为我的游戏获取像素/点的颜色。所以我试图找到一个输入 CGPoint 并返回 Color 的函数,到目前为止我发现的所有内容都只返回 (0,0,0,0)。我认为这是因为我在我的游戏场景类(它是一个 SKScene)中这样做,并且场景仅由 View Controller 加载。任何解决方案?

(如果有更好的方法来检查 sprite 是否接触到同样有效的颜色)

提前致谢。

最佳答案

添加以下方法:

extension UIView {
    func getColor(at point: CGPoint) -> UIColor{

        let pixel = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: 4)
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
        let context = CGContext(data: pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!

        context.translateBy(x: -point.x, y: -point.y)
        self.layer.render(in: context)
        let color = UIColor(red:   CGFloat(pixel[0]) / 255.0,
                            green: CGFloat(pixel[1]) / 255.0,
                            blue:  CGFloat(pixel[2]) / 255.0,
                            alpha: CGFloat(pixel[3]) / 255.0)

        pixel.deallocate(capacity: 4)
        return color
    }
}

你可以得到你想要的点的颜色

let color = someView.getColor(at: somePoint)

关于swift - 在 SKScene swift 中获取点的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42687122/

相关文章:

swift - 如何快速将数据转换为十六进制字符串

ios - 适用于 iOS 的 GoogleMaps SDK - SWIFT 3 : When hiding a marker and then adding the map view back, CPU 卡在 100%

ios - 我怎样才能修好这个炮塔,让它移动平稳

ios - 在 Swift 中使用更新函数的更清洁(更好)替代方法

ios - 雪碧包 : how to make newly spawned enemy ships shoot bullets at player?

ios - 如何从 swift 3 中的键值对中删除符号?

swift - 当固定在 UINavigationBar 下方时,UISearchBar 没有居中

ios - recordID 的值类型为引用,无法查询

ios - 为什么我不能将 UICollectionViewFlowLayout 中的 referenceSizeForFooterInSection 与 EstimateItemSize 一起使用?

swift - Swift 中类型也是对象吗?向对象发送消息的含义是什么