libGDX get pixel color from sprite or texture

荒凉一梦 提交于 2019-12-01 05:31:02

问题


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.

so I have:

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


回答1:


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));
    }
}


来源:https://stackoverflow.com/questions/28405361/libgdx-get-pixel-color-from-sprite-or-texture

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!