Get Color of point in a SKScene swift

你离开我真会死。 提交于 2019-12-06 07:27:51

问题


I need to get the color of a pixel/point for my game in Swift. So I tried to find a function that inputs a CGPoint and returns a Color, everything that I have found so far has only returned (0,0,0,0). I think that this is because I am doing this in my game scene class(which is an SKScene), and the scene is only being loaded by a view controller. Any Solutions?

(If there is a better way to check if a sprite is touching a color that would work as well)

Thanks in advance.


回答1:


Add the below method:

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
    }
}

You can get the color of the point you want with

let color = someView.getColor(at: somePoint)


来源:https://stackoverflow.com/questions/42687122/get-color-of-point-in-a-skscene-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!