libGDX从精灵或纹理获取像素的颜色 [英] libGDX get pixel color from sprite or texture

查看:526
本文介绍了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));
    }
}

这篇关于libGDX从精灵或纹理获取像素的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆