I am trying to draw an outline (a transparent box with colored border essentially)

I have the following code adapted from here

void OnGUI(){
    GUI.Box (new Rect (10,10,200,30), "Object", InitStyles(new Color( 0f, 0f, 0f, 0.0f )));
private GUIStyle InitStyles(Color color){
    GUIStyle currentStyle = null;
    if( currentStyle == null ){
        currentStyle = new GUIStyle (GUI.skin.box );
        currentStyle.normal.background = MakeTex( 2, 2, color );
    return currentStyle;

private Texture2D MakeTex( int width, int height, Color col ){
    Color[] pix = new Color[width * height];
    for( int i = 0; i < pix.Length; ++i ){
        pix[ i ] = col;
    Texture2D result = new Texture2D( width, height );
    result.SetPixels( pix );
    return result;

This is getting rid of the border along with the background color.

Is there a better way to do this?


1 Answer 1


You could use the "9-slicing sprites" technique to cut up a fairly basic sprite texture and use that to draw the borders.

Start by creating a fairly simple sprite - this one is 16x16, but it could easily be smaller, with a white border and transparent centre:
16x16 sprite - white border, transparent centre

Import this into Unity, and on the import settings set the Texture Type to "Sprite (2D and UI)" and the Mesh Type to "Full Rect", Apply and then open the Sprite Editor:
Import settings

In the Sprite Editor, drag the green handles inside your border and Apply:
Inner border defined in sprite editor

You can then apply this texture to a UI Image as the Source Image, making sure you set the Image Type to "Sliced" and clear the "Fill Center" option:
UI Image settings

This results in a nicely scaled, outlined box in game:
UI element in game

By using a white border you can then apply tints via the Color parameter:
Tinted border colour

  • \$\begingroup\$ unfortunately you cannot change the thickness of the border then, can you? \$\endgroup\$
    – SaPropper
    Commented Apr 28, 2022 at 13:38
  • \$\begingroup\$ you can use a bigger png (e.g. 1000x1000) fully filled with white, and then you can adjust the border thickness in the sprite editor :) \$\endgroup\$
    – SaPropper
    Commented Apr 28, 2022 at 14:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .