Specs for Graphics.DrawTexture

I want to implement pixmap fonts in unity. The glyphs are specified in a png file and the file is loaded as a Texture2D.

I need some way to copy a small rectangle of the pixmap image containing a single character to a given position on the screen. For that sake, I thought I could use

Graphics.DrawTexture (screenRect : Rect, texture : Texture, sourceRect : Rect, leftBorder : int, rightBorder : int, topBorder : int, bottomBorder : int, mat : Material = null) : void

but the documentation does not explain what the different parameters are for, and I could not figure them out by testing. When calling (boo code follows):


I would expect the top-left 40x40 pixels of my image to be copied to the top-left 40x40 pixels of the screen. However, all I get is flat gray where the pixels should appear.

Does somebody know how Graphics.DrawTexture is intended to work? Is there another way to blit a rectangle from a texture onto the screen?

I know the texture image is well imported because it looks fine when using this other version of DrawTexture, which does not allow to specify a rectangle within the texture:

Graphics.DrawTexture (screenRect : Rect, texture : Texture, leftBorder : int, rightBorder : int, topBorder : int, bottomBorder : int, mat : Material = null) : void

I thought also of creating one texture for each glyph and drawing that instead. But I think that's a less natural solution.

Try specifying the srcRect parameters in texture coordinate space instead (ie: [0,0,1,1] for the complete texture).

Also, you might want to consider using Unity's built-in font rendering instead, by creating a custom font for your texture. Create an empty font asset from the Create Assets popup, and set up the texture, and the character positions. Then you should be able to use it in any GUI code like any imported font.

Here is an example. This draws the lower left third of the texture in texture coords (range is 0.0 to 1.0, x increases right and y increases up) with origin being in the bottom-left corner of the texture, into a rectangle at (200,100) pixel coords (origin being upper-left corner of the screen) with width and height of 128.

Now as far as pixel-perfect drawing, I haven't achieved that - i.e., there seems to be some stretching no matter what, when source texture dimensions match the destination rectangle dimensions (even trying off by one). Is there a trick to specify coords to avoid any stretching or blurring?

public Texture myTexture;


void OnGUI()
    if (Event.current.type == EventType.Repaint)
            new Rect(200, 100, 128, 128),
            new Rect(0.0, 0.0, 0.3f, 0.3f),
            0, 0, 0, 0);