Search code examples
godotgdscriptgodot4

What does the src_rect parameter in CanvasItem.draw_texture_rect_region() do?


Now, the official documentation sadly only reads:

void draw_texture_rect_region ( Texture2D texture, Rect2 rect, Rect2 src_rect, Color modulate=Color(1, 1, 1, 1), bool transpose=false, bool clip_uv=true )

Draws a textured rectangle region at a given position, optionally modulated by a color. If transpose is true, the texture will have its X and Y coordinates swapped.

I would like to ask what the parameter Rect2 src_rect does.

I am trying to draw a repeating texture into a CanvasItem (a button) and am trying to use the CanvasItem.draw_texture_rect_region() method to do so. Specifically, my function looks like this:

# size_in_cells is the amount of grid cells the object is supposed to use.

# cell_size is the side length of the (square) cell

# blockTexture is the CompressedTexture2D I am using as a texture. As it has a native resolution of 
# 64 by 64 pixels I need to scale it to match the cell_size.

func _draw():
    for i in range(size_in_cells):
        draw_texture_rect_region(blockTexture, \
        Rect2(Vector2((self.get_rect().size.x/size_in_cells)*i,0), Vector2(cell_size, cell_size)),\
        self.get_rect())

Solution

  • src_rect is the region of the given texture to draw onto the canvas item's rect.

    This can be read as "draw pixels from texture source rectangle onto canvas item's destination rectangle."

    Examples:

    1. You want to draw the whole texture onto the canvas at position (10, 10) with size (100, 100).
    var dst_rect = Rect2(10, 10, 100, 100)
    var src_rect = Rect2(Vector2(), texture.get_size())
    draw_texture_rect_region(texture, dst_rect, src_rect)
    
    1. The texture is an atlas with a row of 3 images. Each image is 32x32 pixels. You want to draw the second image on the canvas at position (64, 64) with size (32, 32).
    var image_index = 1
    var dst_rect = Rect2(64, 64, 32, 32)
    var src_rect = Rect2(32 * image_index, 0, 32, 32)
    draw_texture_rect_region(texture, dst_rect, src_rect)
    

    Hope this helps.