libGDX从精灵或纹理获取像素的颜色

libGDX从精灵或纹理获取像素的颜色

问题描述:

我正在寻找它的净,但我没能找到任何解决办法。我有一个精灵或纹理,当我触摸它,我想要得到的像素颜色从触摸坐标。

I was searching it on net but i wasn't able to find any solution. I have a sprite or a texture and when i touch it i want to get pixel color from touch coordinates.

所以我有:

 if (Gdx.input.isTouched()) {
            Rectangle spriteBounds = sprite.getBoundingRectangle();
            if (sprite.contains(Gdx.input.getX(), Gdx.input.getY())) {
                //and here something like
                //Color color = sprite.getPixelColor(Gdx.input.getX(), Gdx.input.getY());
            }
        }

这可能吗?谢谢:)

Is it possible? Thank you :)

像下面这样可能会奏效,但没有经过检验。您可以通过精灵的纹理像素图得到的颜色。你需要确保你转换的输入(屏幕)妥善协调纹理的本地坐标。

Something like the following might work, but is untested. You can get the color via the Pixmap of the sprite's Texture. You need to make sure that you are converting the input (screen) coordinates properly to the local coordinates of the texture.

if (Gdx.input.isTouched()) {
    Rectangle spriteBounds = sprite.getBoundingRectangle();
    if (spriteBounds.contains(Gdx.input.getX(), Gdx.input.getY())) {
        Texture texture = sprite.getTexture();

        int spriteLocalX = (int) (Gdx.input.getX() - sprite.getX());
        // we need to "invert" Y, because the screen coordinate origin is top-left
        int spriteLocalY = (int) ((Gdx.graphics.getHeight() - Gdx.input.getY()) - sprite.getY());

        int textureLocalX = sprite.getRegionX() + spriteLocalX;
        int textureLocalY = sprite.getRegionY() + spriteLocalY;

        if (!texture.getTextureData().isPrepared()) {
            texture.getTextureData().prepare();
        }
        Pixmap pixmap = texture.getTextureData().consumePixmap();
        return new Color(pixmap.getPixel(textureLocalX, textureLocalY));
    }
}