I have a texture , the type is Sprite (2D and UI) , sprite mode : Single , it is a 9-sliced-Sprite , but when i draw the texture , it seem like it was acting like a normal texture , not a 9-sliced-Sprite , the size of the edges of the texture is still increasing. I am trying to make a Drag Selection Box. This is my code :
public void OnGUI()
if (isDragging && !Paused)
Texture te = (Texture)Resources.Load(Paths.UIRectPath + "/SelectedRect");
GUI.DrawTexture(new Rect(beforeVector.x, Screen.height - beforeVector.y, Input.mousePosition.x - beforeVector.x, beforeVector.y - Input.mousePosition.y) , te);
// . . .
isDragging = true;
beforeVector = Input.mousePosition;
else if (Input.GetMouseButtonUp(0))
isDragging = false;
beforeVector = new Vector3();
How can i draw a sliced sprite (or texture) without creating a UI image in the canvas ? I tried using this method . but the image position and size is weird. This is one using UI image :
Rect tt = new Rect(beforeVector.x, Screen.height - beforeVector.y, Input.mousePosition.x - beforeVector.x, beforeVector.y - Input.mousePosition.y);
SelectionRect.GetComponent<RectTransform>().sizeDelta = tt.size;
SelectionRect.GetComponent<RectTransform>().localPosition = tt.position;
DrawTexture can’t draw a 9-sliced image. Where do you think you specified the size of the border?
You can draw a 9-sliced image by using a GUIStyle. You can create a GUIStyle either by:
- creating a GUISkin. This might be the best way when you have more than one such texture
- using a public variable of type GUIStyle. Best approach for a single image when you like setting things up in the inspector
- initialize the style at runtime via code.
What you have to do is:
- assigning your testure as background image to the “normal” state.
- set your pixel border for each edge in the “border” setting of the style. So you specify here how many pixel from left, from right, top and bottom should be fixed.
- Finally just use the style either to draw any of the built-in elements (GUI.Label for example), or draw the style manually by calling one of it’s
Draw() methods during the Repaint event.
To initialize at runtime you can do something like:
public Texture2D myTexture;
GUIStyle myStyle = null;
if (myStyle == null)
myStyle = new GUIStyle("label"); // copy all settings of the label style
myStyle.normal.background = myTexture;
myStyle.border = new RectOffset(20, 20, 20, 20);
if (Event.current.type == EventType.Repaint)
myStyle.Draw(new Rect(/*Your rect here*/), false, false, false, false);
// or something like this:
GUI.Label(new Rect(/*Your rect here*/), "", myStyle);
If you created a GUISkin asset you would do something like this instead:
public GUISkin mySkin;
GUI.skin = mySkin;
GUI.Label(new Rect(/*Your rect here*/), "", "YourStyleName");