LibGDX - create a border around the image

Is it possible to create a border around an image? I have many blocks in 2D, and when a player hovers over one of them, I want to display a frame around the texture / image.

This is how I actually drew the block (I don’t think it matters, but maybe this will help):

batch.draw(map.map[mapPos].TEXTURE, (mapPosX * Block.WIDTH), (mapPosY * Block.HEIGHT), Block.WIDTH, Block.HEIGHT); 

Is this possible with the code or should I make a separate image with a texture and a border around it? Any ideas?

+7
java textures libgdx
source share
2 answers

You can try using ShapeRenderer to draw the border first, then batch.draw above it. This is done exclusively in code, without using texture. The blue frame is added in the code below.

In render() add the following after batch.end() .

 batch.end(); // Add the following after this line sr.setProjectionMatrix(camera.combined); sr.begin(ShapeType.Line); sr.setColor(new Color(0,0,1,0)); sr.rect((mapPosX * Block.WIDTH), (mapPosY * Block.HEIGHT), Block.WIDTH, Block.HEIGHT)); sr.end(); 

Of course, you need to initialize the ShapeRenderer in your implementation of Screen or ApplicationListener . Just do it in the code where you declare and initialize the package.

In the class Game:

 SpriteBatch batch; //Put the following below this line ShapeRenderer sr; 

In your constructor:

 batch = new SpriteBatch(); //Put the following below this line sr = new ShapeRenderer(); 

edit: I rewrote the function so that you can draw the shape after drawing the texture pack.

+4
source share

I would recommend one of these two approaches:

  • Make two different images: one with a frame, one without - for each image that needs this freezing functionality; this is a way to display button images - a separate image for a normal, pressed, hovering or any other.
  • If you have many different images of the same size (or “blocks”, as you put it) that need this border, less work and less memory, if you implement a single “border texture” and render it with your original texture " block "when the mouse hangs over it.

This is my personal opinion, but I never liked creating a form in libgdx. I forgot how to use the shape renderer, but if you need to set up the projection matrix as in nedR's answer, the way I described will also be faster.

+4
source share

All Articles