A few weeks earlier I was confused in how to use the DrawTextureWithTexCoords, searching with google gave no results, yes there are fews example and perhaps tips, but those are unclear to me.
Fortunatelly after trial and error, I finally understand how this function really works, stick to me for more explanation.
Unity Documentation :
DrawTextureWithTexCoords(Rect position, Texture image, Rect texCoords, bool alphaBlend = true);
Position : Rectangle on the screen to draw the texture within.
Texture : Texture to display.
texCoords : How to scale the image when the aspect ratio of it doesn’t fit the aspect ration to be drawn within.
alphablend : Whether to alpha blend the image on to the display (the default). If false, the picture is drawn on the display.
For more simple explanation,
The position is the size of your device resolution ( 480×800, 600×1024 ) in new Rectangle like (position x, position y, sizeWidth, sizeHeight).
The Texture is the image you want to use for drawing.
The texCoords is the size of the image and position of the x y in the texture image.
alphaBlend, I guess this is for transparent ? set it to true.
Then how to use it ? hold on a minute, I will give you a detailed example on this part.
Let’s say that we have an image of 1600 x 1080 ( width x height ), and the device resolution is ( 480 x 800 ), how can we make it responsive to other resolution in unity ?
example code in c#
1 2 3 4 5 6 7 8 9 10 11 12 13 |
float deviceWidth; float deviceHeight; float imageWidth = 1600f; float imageHeight = 1080f; public Texture aTexture; // get device width and height deviceWidth = (float)Screen.width; deviceHeight = (float)Screen.height; GUI.DrawTextureWithTexCoords(new Rect(0, 0, deviceWidth, deviceHeight), aTexture, new Rect(0, 0, deviceWidth / imageWidth, deviceHeight / imageHeight), true); |
with the code U will get a 480 x 800 image size from bottom left texture, to for example setting to middle in the image, you must set the x, y in the new Rect in TexCoords.
Be careful, for using gui.drawtexturewithcoord, you need to set the position and size with float on the texCoords, where the full size is presented with 1f, so in texCoords you actually must write it like this new Rect(0f, 0f, 0.3f, 0.24f).
Btw, this here is example on how to get to the center of the image
1 2 3 4 5 6 7 |
// get the width position in pixel divided by imagewidth pixel to get the zero point xx ( 0.xx ) position_x = ((imageWidth / 2) - (deviceWidth / 2)) / imageWidth; // same as above but with height position_y = ((imageHeight / 2) - (deviceHeight / 2)) / imageHeight; |
There you go, fairly simple eh ? if you had any question just fill in the box comment.
PS: For you newbies out there like me, You probably wonder why using 1f in draw texture sometimes resulting in the image feel like stretched, that’s because your image is still in sprite mode, you need to change it to texture.