Search code examples
swiftsprite-kitswift3uicolorcgpoint

Get Color of point in a SKScene swift


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.


Solution

  • 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)