Graphics.DrawTexture not at the right size

Hello everyone,

I am trying to draw a texture2D (brush) into another texture (stencil) but I am encountering strange issues. The brush is strangely deformed. First I though is was comming from the screen size, but could not make it work. I am working in the Editor and not in Game mode.

I tried to adjust the brush size with some ratios of:
-Screen.width, Screen.height (for example here I had 680, 1273) Which is strange the width is inferior to height?
-Screen.currentResolution.width, Screen.currentResolution.width (Here 2560x1440)

but the ratio is off, I manualy tried to get the good one and I had something like 1151x747??? Which is corresponding to nothing I have. And when I change the editor window size, it changes.

Maybe it comes from the Screen.width/Screen.height which does not seems good.

Here is the code:

    void AddToStencil(Texture2D stencil, Texture2D brush, Vector2 brushPosition, int brushSizePixels)
    {
        //Create temporary render texture
        int width = stencil.width;
        int height = stencil.height;
        RenderTexture rt = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.ARGB32);

        //Copy existing stencil to render texture (blit sets the active RenderTexture)
        Graphics.Blit(stencil, rt);

        //Draw the brush at position
        Graphics.DrawTexture(new Rect(brushPosition.x, brushPosition.y, brushSizePixels, brushSizePixels), brush);

        //Read texture back to stencil
        stencil.ReadPixels(new Rect(0, 0, width, height), 0, 0, false);

        stencil.Apply();
        RenderTexture.active = null;
        rt.Release();
    }

If someone can help me understand it would be great!

For information I am using the 2021.1.22f1 version of Unity

Thanks for reading.

Graphics.DrawTexture doesn’t set up the matrix. It basically emits a quad with the coordinates you specified. So you have to set the matrices before you draw ( see here for more info How do I call Graphics.DrawTexture correctly? - Questions & Answers - Unity Discussions). So the code should look something like:

        //Copy existing stencil to render texture (blit sets the active RenderTexture)
        Graphics.Blit(stencil, rt);
        GL.PushMatrix();
        GL.LoadPixelMatrix(0, width, height, 0);
        //Draw the brush at position
        Graphics.DrawTexture(new Rect(brushPosition.x, brushPosition.y, brushSizePixels, brushSizePixels), brush);
        GL.PopMatrix();
4 Likes

Amazing! Thank you very much, I tried some things with the GL library but did not fully understand what I was doing.