4
\$\begingroup\$

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 );
    result.Apply();
    return result;
}

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

Is there a better way to do this?

\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.