How to get pixel color by touch inside SKScene?

I have a spritekit application written in swift and I want to get the color on the pixel that touches my finger.

I saw several posts about this and tried them all, but couldn't seam to make it work for me. In addition to another post, he must get the color from UIView, and since SKScene has a SKIView that inherits from UIView, he should be able to get the color from there.

So, to simplify and understand the question, I have an example.

Create a new spritekit application and add an image to it. In my case, I created a png image of 200x200 pixels in size with many different colors in it.

This is the GameScene.swift file, it is the only file that I have automatically generated:

import SpriteKit extension UIView { func getColorFromPoint(point:CGPoint) -> SKColor { var pixelData:[UInt8] = [0,0,0,0] let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.toRaw()) let context = CGBitmapContextCreate(&pixelData, 1, 1, 8, 4, colorSpace, bitmapInfo) CGContextTranslateCTM(context, -point.x, -point.y); self.layer.renderInContext(context) var red:CGFloat = CGFloat(pixelData[0])/CGFloat(255.0) var green:CGFloat = CGFloat(pixelData[1])/CGFloat(255.0) var blue:CGFloat = CGFloat(pixelData[2])/CGFloat(255.0) var alpha:CGFloat = CGFloat(pixelData[3])/CGFloat(255.0) var color:SKColor = SKColor(red: red, green: green, blue: blue, alpha: alpha) return color } } class GameScene: SKScene { var myColorWheel:SKSpriteNode! override func didMoveToView(view: SKView) { let recognizerTap = UITapGestureRecognizer(target: self, action:Selector("handleTap:")) view.addGestureRecognizer(recognizerTap) myColorWheel = SKSpriteNode(imageNamed: "ColorWheel.png") myColorWheel.anchorPoint = CGPoint(x: 0, y: 0) myColorWheel.position = CGPoint(x: 200, y: 200) self.addChild(myColorWheel) } func handleTap(recognizer : UITapGestureRecognizer) { let location : CGPoint = self.convertPointFromView(recognizer.locationInView(self.view)) if(myColorWheel.containsPoint(location)) { let color = self.view?.getColorFromPoint(location) println(color) } } } 

It doesn't matter where I click on the image on the display, the result is always: Optional(UIDeviceRGBColorSpace 0 0 0 0)

+5
source share
1 answer

You tried to take a snapshot first using:

 - (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates 

Then choose the colors from this point of view?

Not sure how the system displays .layer in SKView.

Hope this helps.

Greetings

0
source

Source: https://habr.com/ru/post/1206658/


All Articles