How to get pixel color from SKSpriteNode or from SKTexture?

前端 未结 3 1708
南笙
南笙 2020-12-04 00:16

I want to get precise selection of my object on game map. Object is a sprite with which has some transparent pixels around and I want to test touch location for these transp

3条回答
  •  猫巷女王i
    2020-12-04 00:55

    Here is how to get the color of one pixel directly from the SKTexture:

    class SpriteKitUtility
    {
        class func pixelFromTexture(texture: SKTexture, position: CGPoint) -> SKColor {
            let view = SKView(frame: CGRectMake(0, 0, 1, 1))
            let scene = SKScene(size: CGSize(width: 1, height: 1))
            let sprite  = SKSpriteNode(texture: texture)
            sprite.anchorPoint = CGPointZero
            sprite.position = CGPoint(x: -floor(position.x), y: -floor(position.y))
            scene.anchorPoint = CGPointZero
            scene.addChild(sprite)
            view.presentScene(scene)
            var pixel: [Byte] = [0, 0, 0, 0]
            let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
            let context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, CGColorSpaceCreateDeviceRGB(), bitmapInfo);
            UIGraphicsPushContext(context);
            view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
            UIGraphicsPopContext()
            return SKColor(red: CGFloat(pixel[0]) / 255.0, green: CGFloat(pixel[1]) / 255.0, blue: CGFloat(pixel[2]) / 255.0, alpha: CGFloat(pixel[3]) / 255.0)
        }
    }
    

提交回复
热议问题