Get Color of Point in a Skscene Swift

Get Color of point in a SKScene swift

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)

How to change the background colour of SKScene?

The problem is that you are trying to set color in 8 bit 255 rgb, but UIColor accepts floating point value eg 0 ... 1.0.

Transform your values to floating point values.

self.backgroundColor = UIColor(red: 0.157, green: 0.157, blue: 0.157, alpha: 1.0) 

How to get pixel color from SKSpriteNode or from SKTexture?

In Sprite Kit you don't have access to texture data.

Instead you'd have to create a bit mask from the image, for example by loading the image as UIImage or CGImage and scanning for all non-transparent pixels.

How to get the color of a pixel in an UIView?

It is pretty horrible and slow. Basically you create a bitmap context with a backing store you allocate so you can read the memory, then you render the views layer in the context and read the appropriate point in ram.

If you know how to do it for an image already you can do something like this:

- (UIImage *)imageForView:(UIView *)view {
UIGraphicsBeginImageContext(view.frame.size);
[view.layer renderInContext: UIGraphicsGetCurrentContext()];
UIImage *retval = UIGraphicsGetImageFromCurrentImageContext(void);
UIGraphicsEndImageContext();

return retval;
}

And then you will get an image where you can get the pixel data. I am sure the mechanism you have for dealing with images involves rendering them into a context anyway, so you can merge that with this and factor out the actual image creation. So if you take that could and remove the bit where you load the image and replace it with the context render:

[view.layer renderInContext: UIGraphicsGetCurrentContext()];

you should be good.



Related Topics



Leave a reply



Submit