- Home /
Select part of the texture in GUI.DrawTexture
Hi guys, how are you? So, I need help to solution a problem in my game, how do I make to select just a part of the texture in GUI.DrawTexture and don't to show the rest? thanks a lot!
can you elaborate please? Are you wanting to show half of the texture, a single sprite out of a sprite sheet, etc...?
I'm wanting to show a part of the image. Example: A image with 300x200 I wanna show of the 0px to 50px and of the 0px to 80px
Answer by Molix · Aug 29, 2011 at 02:33 PM
You could use a GUI.BeginGroup to crop it, e.g.
public Texture2D texture;
public Rect textureCrop = new Rect( 0.1f, 0.1f, 0.5f, 0.25f );
public Vector2 position = new Vector2( 10, 10 );
void OnGUI()
{
GUI.BeginGroup( new Rect( position.x, position.y, texture.width * textureCrop.width, texture.height * textureCrop.height ) );
GUI.DrawTexture( new Rect( -texture.width * textureCrop.x, -texture.height * textureCrop.y, texture.width, texture.height ), texture );
GUI.EndGroup();
}
Answer by IsGreen · Jun 13, 2014 at 07:49 PM
Using GUI.DrawTextureWithTexCoords
Parameters
position: Represent position and "total" size of texture. texCoords: Use percentage per unit. Relative Left-Lower corner, and relative scale.
Axes Origin
OnGUI origin is Left-Upper corner: position parameter use this origin. But, in DrawTextureWithTexCoords the origin is Left-Lower corner: texCoords use this origin.
With texCoords parameter you can crop(percentage between 0-1) or tile image (width or height upper to 1).
To maintain aspect, also you must change "total" size of texture(position parameter).
Before this, you need save texture initial size(width,height).
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class NewBehaviourScript : MonoBehaviour {
public Texture image;
[Range(0f,1f)]
public float x=0f;
[Range(0f,1f)]
public float y=0f;
[Range(0f,1f)]
public float width=1f;
[Range(0f,1f)]
public float height=1f;
float initialWidth,initialHeight;
bool imageEnabled=false;
void Update(){
if(!this.imageEnabled) if(this.image!=null){
this.initialWidth = this.image.width;
this.initialHeight = this.image.height;
this.imageEnabled=true;
}
}
void OnGUI(){
if(imageEnabled){
Rect position = new Rect(0f,0f,this.initialWidth*this.width,this.initialHeight*this.height);
Rect coords = new Rect(this.x,this.y,this.width,this.height);
GUI.DrawTextureWithTexCoords(position,this.image,coords);
}
}
}