How to crop a texture from a tilemap/tileset data?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Edgar Alvarado

I want to create a texture cropped from the texture used by a tileset.

I have this code:

var txr = _tile_map.tile_set.tile_get_texture(id)
var img = txr.get_data()
var imgDest = Image.new()
imgDest.blit_rect(img, Rect2(0, 0, 128, 128), Vector2(0, 0))
var imgTxr = ImageTexture.new()
imgTxr.create_from_image(imgDest)
btn.texture_normal = imgTxr

When using txr directly it works fine… But the whole texture is used and I want it the button to have it cropped to the tile size.

While debugging I found txr.get_data() returns [null]

Why is this happening?
Is there another way to corp a texture retrieved from a tileset?

:bust_in_silhouette: Reply From: ivanskodje

You can use AtlasTexture for this.

Your code would look something like this:

var texture = _tile_map.tile_set.tile_get_texture(id)
var region_to_crop = Rect2(0, 0, 128, 128)
var atlas_texture = AtlasTexture.new()
atlas_texture.set_atlas(texture)
atlas_texture.set_region(region_to_crop)
btn.texture_normal = atlas_texture

An alternative way to write the same code:

func your_function_here():
	var texture := _tile_map.tile_set.tile_get_texture(id)
	var region_to_crop := Rect2(0, 0, 128, 128)
	btn.texture_normal = get_cropped_texture(texture, region_to_crop)

func get_cropped_texture(var texture : Texture, var region : Rect2) -> AtlasTexture:
	var atlas_texture = AtlasTexture.new()
	atlas_texture.set_atlas(texture)
	atlas_texture.set_region(region)
	return atlas_texture