- Home /
Rendering a portion of a texture using GUI.Box()?
Hi,
I have a texture that is 256x64. I need to render from 0,0 to 63,63 in this texture (A 64x64 sub-rect). How can I do this using GUI.Box()?
I've tried specifying a GUIStyle that sets contentOffset to (0,0) and fixedWidth/fixedHeight to 64,64 but this didn't work.
Thanks.
Answer by rlbaldi · Mar 22, 2010 at 02:36 PM
Take a look at Graphics.DrawTexture.
http://unity3d.com/support/documentation/ScriptReference/Graphics.DrawTexture.html
You can specify a material and, with so, UV coordinates. This way you can draw only a portion of your texture inside OnGUI calls. You must end up with something like it:
if (Event.current.type == EventType.Repaint)
{
Graphics.DrawTexture(screenRect, texture, new Rect(u, v, uWidth, vHeight), leftBorder, rightBorder, topBorder, bottomBorder, material);
}
Where
new Rect(u, v, uWidth, vHeight)
is your sourceRect (texture portion that you want to draw).
Answer by Molix · Apr 19, 2010 at 04:54 PM
I think you can use GUI.DrawTexture, e.g. (C#):
// Edited - Sorry for the mistake. Here's an example of updating the pixels as described elsewhere: //OnGUI() //{ // GUI.DrawTexture( myRect, myTexture, ScaleMode.ScaleAndCrop ); //}
Color[] colors = textureToCrop.GetPixels( (int)cropRect.x, (int)cropRect.y, (int)cropRect.width, (int)cropRect.height ); croppedTexture = new Texture2D( (int)cropRect.width, (int)cropRect.height ); croppedTexture.SetPixels( colors ); croppedTexture.Apply( false );
That will still scale the texture, it will just crop if the aspect ratio of the new dimensions don't match. This won't work.
As specified in the question, the aspect ratio does not match. However, this centers the texture on the other axis, so is not applicable.
I'll edit above to remove the problem.
Answer by naruse · Mar 22, 2010 at 02:13 PM
There are several ways, copy only that part of the texture to a new texture using GetPixels (or something like that I dont remember pretty well now).
another one is render to texture from another camera only that part of the texture (which I think is kinda hacky)
I would use the 1rst one I suggested you.
Answer by qJake · May 31, 2010 at 09:31 PM
Naruse was correct, although I will flesh out his answer a bit:
Use Texture2D.GetPixels to get the area of pixels you want. Then, create a new Texture2D object, and call Texture2D.SetPixels to write the extracted section of pixels to the new texture object. Then, call GUI.Box()
or GUI.Texture()
or whatever else you want to use, but using the new Texture2D object you created instead of the old one.
Answer by MorphVGX · Nov 14, 2011 at 09:19 PM
My question would be. Do I gain something from having all my textures in a single, let's say, png file then do this to create subtextures to apply? Or it is better if the textures are split by the artist?