ICP
ICP

Reputation: 97

How to take a section of an image (.png) and store it as a texture in libGDX

So the title pretty much says it all...

I am working on a libGDX project that will require me to take a section(for example: take 100x100 chunk out of a 2000x2000 image) of different images and store it as a libGDX texture.

The end goal is to take this texture and fill a polygon with it.

I know that I could format these images by hand, but this is no good. New images will be used all the time. And there are to many sections to be taken from each.

I have been looking through the libGDX api and have found nothing. Either I am looking in the wrong place or I am looking for the wrong thing. I would be happy with just a nudge in the right direction.

Thanks

Upvotes: 1

Views: 1624

Answers (2)

dfour
dfour

Reputation: 1376

As icarumbas said you can use TextureRegion. The TextureRegion will hold a reference to a texture where the region is stored as well as the width, height, x position and y position of the image in the texture. There is no need to split the image into separate textures as a TextureRegion is intended to store a region of a texture without having to create more textures.

Example:

Texture wholeImage = new Texture("imagePath");
TextureRegion firstRegion = new TextureRegion(wholeImage,0,0,50,50); // gets the region from the 0,0 point of the whole image and is 50 x 50px
TextureRegion secondRegion = new TextureRegion(wholeImage,0,50,50,50); // gets the region from the 0,50 point of the whole image and is 50 x 50px
TextureRegion topRegion = new TextureRegion(wholeImage,50,0,100,50); // gets the region from the 50,0 point of the whole image and is 100 x 50px

These can then be drawn the same way as a normal texture can be drawn with a spritebatch

batch.begin();
batch.draw(firstRegion, 30,30);
batch.draw(secondRegion , 130,30);
batch.draw(topRegion , 130,130);
batch.end();

A common issue when using TextureRegions is when people use the getTexture() method. This method is for getting the whole texture not the region defined.

Upvotes: 3

icarumbas
icarumbas

Reputation: 1815

You can use TextureRegion split(..) method.

TetureRegion reg = new TextureRegion(new Texture("pathToYourImage"));
TextureRegion[][] subRegions = reg.split(100, 100); 

This will create tiles out of this TextureRegion starting from the top left corner going to the right and ending at the bottom right corner.

UPD: If your regions have different size or not placed in a grid. Use Pixmap drawPixmap(..) method.

int sectionWidth = ...
int sectionHeight = ...
int sectionSrcX = ...  
int sectionSrcY = ... 

Pixmap allTexture = new Pixmap(Gdx.files.internal("path"));

Pixmap section = new Pixmap(sectionWidth, sectionHeight, Pixmap.Format.RGBA8888);

section.drawTexture(0, 0, sectionSrcX, sectionSrcY, sectionWidth, sectionHeight);

Texture cutTexture = new Texture(section);

Upvotes: 2

Related Questions