libGDX get pixel color from sprite or texture(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());
}
}
有可能吗?谢谢你:)
推荐答案
类似以下的方法可能有效,但未经测试.您可以通过 sprite 的 Texture
的 Pixmap
获取颜色.您需要确保将输入(屏幕)坐标正确转换为纹理的本地坐标.
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 从精灵或纹理中获取像素颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!