Draw circles or primitives on the new UI canvas?

Hi, I’m trying to build a Circular Health bar and I was wondering if it’s possible to draw Circles/Arcs or primitives like lines into the canvas so I can create my Circular HealthBar ?

Regards

E

1 Like

There’s no support for primitives right now. You can, however, use an image and a Radial Fill to make a circular health bar.

If you want to get into the nitty gritty of the UI it’s also possible to write a component that extends from some UI classes and builds your own mesh. I haven’t gotten into that yet though, so I can’t really give you advice on getting started.

Yes; I’ve done this, its not all that hard. The only gotcha when making circle is that the OnFillVBO function expects you to send quads only (no triangles) so you will be sending extra geometry.

Here’s the docs with a complete example:
http://docs.unity3d.com/460/Documentation/ScriptReference/UI.Graphic.html

Well, not completely unsupported. You can take any object and replace the Transform component with a RectTransform and the anchors seem to be working for the most part. It’s not perfect but I can pretty much put anything into my canvas. Keep in mind my canvas is camera based not overlay, and also if you add some 3D objects the z-axis will most likely need to be adjusted.

That said, a specific fill pattern on an Image object or script drawing with a Graphic subclass is probably the most reliable.

1 Like

Just wrote a class that allows to make a circle in edit mode based on example above. It can be filled or not and you can edit the “fill angle” for it. The code should be optimized

using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;


[ExecuteInEditMode]
public class UICircle : Graphic
{ 
    [Range(0,100)]
    public int fillPercent;
    public bool fill = true;
    public int thikness = 5;

    void Update(){
        this.thikness = (int)Mathf.Clamp(this.thikness, 0, rectTransform.rect.width/2);
    }

    protected override void OnFillVBO (List<UIVertex> vbo){
        float outer = -rectTransform.pivot.x * rectTransform.rect.width;
        float inner = -rectTransform.pivot.x * rectTransform.rect.width + this.thikness;

        vbo.Clear();

        UIVertex vert = UIVertex.simpleVert;
        Vector2 prevX = Vector2.zero;
        Vector2 prevY = Vector2.zero;

        float f = (float)(this.fillPercent/100f);
        int fa = (int)(361 * f);

        for(int i=0; i<fa; i++){
            float rad = Mathf.Deg2Rad * i;
            float c = Mathf.Cos(rad);
            float s = Mathf.Sin(rad);
            float x = outer * c;
            float y = inner * c;
            vert.color = color;
            vert.position = prevX;
            vbo.Add(vert);
            prevX = new Vector2(outer * c, outer * s);
            vert.position = prevX;
            vbo.Add(vert);
            if(this.fill){
                vert.position = Vector2.zero;
                vbo.Add(vert);
                vbo.Add(vert);
            }
            else{
                vert.position = new Vector2(inner * c, inner * s);;
                vbo.Add(vert);
                vert.position = prevY;
                vbo.Add(vert);
                prevY = new Vector2(inner * c, inner * s);
            }
        }
    }
}

Also it can be done using shaders. The main goal of this one is to draw a non-filled circle with constant border thickness. So it won’t change while you resize the rect :slight_smile:

1 Like

Thank you for this NoxCaos.

I was wondering if anyone could point me in the right direction to add a texture to this? I think I’ve managed to assign UVs, but not sure how to draw an image to them.

Got it figured out. Just had to add this:

    [SerializeField] Texture m_Texture;

    public override Texture mainTexture
    {
        get
        {
            return m_Texture == null ? s_WhiteTexture : m_Texture;
        }
    }


    /// <summary>
    /// Texture to be used.
    /// </summary>
    public Texture texture
    {
        get
        {
            return m_Texture;
        }
        set
        {
            if (m_Texture == value)
                return;
           
            m_Texture = value;
            SetVerticesDirty();
            SetMaterialDirty();
        }
    }

Hmm, must have missed this one.
@NoxCaos & @zge are you ok with this being added to the UI Extensions repo?
Granted has to also be updated for the new 5.2 way of doing things but I can sort that.

Would also be good to add several more primitives as well I think.

As far as my contribution, it’s just copied from Image.cs.

I used this as a base to create a circular timer with a dynamic number of segments. For some reason the first segment in this code always had a vertex in the first poly at 0,0 even when set to not filled. I couldn’t quite figure out why so I’ve had to do some messy stuff to set the first vertices in the correct position when not filled.

I’m happy to send you what I’ve done if it’ll help.

Yup, either push it as a PR to the repo, or I’ll just grab your code above.
Might be better as a UI primative library with a few different shapes.

You can also check out the LineRenderer component already in the UI Extensions repo if you need any tips for rendering raw vertices. (note in 5.2, it all changes!!)

Is it possible to somehow optimize a UI circle? I’m working for mobile and don’t want to use 5MB textures to get a sharp circle.

A primative library would be great, but equilateral shapes can be easily generated using this code, just by changing the number of segments.

Add this:

  public int segments = 360;

and change to this:

        float f = (float)(this.fillPercent/100f);
        float degrees = (float)360f / segments;
        int fa = (int)( (segments + 1) * f);

       
        for(int i=0; i<fa; i++){
            float rad = Mathf.Deg2Rad * (i*degrees);

I did have rendering vertices figured out until 5.2 removed onFillVBO :stuck_out_tongue: I’ll be checking out the new Image and lineRenderer to figure out the new methods.

@Shushustorm NoxCaos code above draws a UI circle without any textures. You can customize it if you need it to be smoother or lower resolution.

1 Like

PS I just realized my earlier contribution was stolen from your UILineRenderer, not Image.cs…

Thanks for pointing this out. I would prefer being able to see the UI in the Editor while working on it, though. It’s very hard for me to build up UI if I don’t see it. So a solution using UI elements would be great.

Being able to use UV-mapped 2d meshes for UI isn’t a planned feature, is it?

I’m actually 95% done with mine that I will be submitting to the Asset Store in a day or two if all goes well. =)

Aaaand that’s my final 5%. :wink:

1 Like

@Shushustorm This is a UI element and is fully editable and visible in the editor. You can also easily add textures. Text and UI images are just UV mapped 2d meshes like this is. Just add a UI panel and put the script on it, and play with the settings…

I’ve also updated it to work with 5.2:

using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
[ExecuteInEditMode]
public class UICircle2 : Graphic
{
    [SerializeField]
    Texture m_Texture;
    [Range(0, 100)]
    public int fillPercent;
    public bool fill = true;
    public int thikness = 5;
    [Range(0, 360)]
    public int segments = 360;
    public override Texture mainTexture
    {
        get
        {
            return m_Texture == null ? s_WhiteTexture : m_Texture;
        }
    }
    /// <summary>
    /// Texture to be used.
    /// </summary>
    public Texture texture
    {
        get
        {
            return m_Texture;
        }
        set
        {
            if (m_Texture == value)
                return;
            m_Texture = value;
            SetVerticesDirty();
            SetMaterialDirty();
        }
    }
    void Update()
    {
        this.thikness = (int)Mathf.Clamp(this.thikness, 0, rectTransform.rect.width / 2);
    }
    protected UIVertex[] SetVbo(Vector2[] vertices, Vector2[] uvs)
    {
        UIVertex[] vbo = new UIVertex[4];
        for (int i = 0; i < vertices.Length; i++)
        {
            var vert = UIVertex.simpleVert;
            vert.color = color;
            vert.position = vertices[i];
            vert.uv0 = uvs[i];
            vbo[i] = vert;
        }
        return vbo;
    }
    //    protected override void OnFillVBO(List<UIVertex> vbo)
    protected override void OnPopulateMesh(Mesh toFill)
    {
        float outer = -rectTransform.pivot.x * rectTransform.rect.width;
        float inner = -rectTransform.pivot.x * rectTransform.rect.width + this.thikness;
        //        vbo.Clear();
        toFill.Clear();
        var vbo = new VertexHelper(toFill);
        UIVertex vert = UIVertex.simpleVert;
        Vector2 prevX = Vector2.zero;
        Vector2 prevY = Vector2.zero;
        Vector2 uv0 = new Vector2(0, 0);
        Vector2 uv1 = new Vector2(0, 1);
        Vector2 uv2 = new Vector2(1, 1);
        Vector2 uv3 = new Vector2(1, 0);
        Vector2 pos0;
        Vector2 pos1;
        Vector2 pos2;
        Vector2 pos3;
        float f = (this.fillPercent / 100f);
        float degrees = 360f / segments;
        int fa = (int)((segments + 1) * f);
        for (int i = 0; i < fa; i++)
        {
            float rad = Mathf.Deg2Rad * (i * degrees);
            float c = Mathf.Cos(rad);
            float s = Mathf.Sin(rad);
            float x = outer * c;
            float y = inner * c;
            uv0 = new Vector2(0, 1);
            uv1 = new Vector2(1, 1);
            uv2 = new Vector2(1, 0);
            uv3 = new Vector2(0, 0);
            pos0 = prevX;
            pos1 = new Vector2(outer * c, outer * s);
            if (fill)
            {
                pos2 = Vector2.zero;
                pos3 = Vector2.zero;
            }
            else
            {
                pos2 = new Vector2(inner * c, inner * s);
                pos3 = prevY;
            }
            prevX = pos1;
            prevY = pos2;
            vbo.AddUIVertexQuad(SetVbo(new[] { pos0, pos1, pos2, pos3 }, new[] { uv0, uv1, uv2, uv3 }));
        }
        if (vbo.currentVertCount > 3)
        {
            vbo.FillMesh(toFill);
        }
    }
}

@Senshi There are a couple of things I’d add to this to make it a more fully functioning shape library. The version I’m using has a few more UV mapping options like slice etc, and discrete segments which was the whole reason for me making it. I needed a radial fill where I could control the edges instead of just an aliased cut-off.

Good luck with yours :slight_smile:

5 Likes

@zge Oh, alright! I thought it would only be drawn when running the game. Thanks for that solution!

Good stuff @Senshi wish you all the best with that asset :smile:

1 Like

@zge this script is awesome! One issue for me is that I’d like to use a material on it and it’s not working out… any idea why it disappears when I add a material?

@zge Great script! One issue I noticed is that if you attempt to fill the circle completely, the epicentre is not filled in, causing a small dot of transparent background to show through. This was noticeable for me because there was another UI element behind it of a different colour.

I believe the root of the issue stems from how thickness is being clamped. It’s possible that a very small amount is never accounted for. My quick fix was to add +1 after dividing the recttransform in two. This isn’t the right solution, but it worked for my case. Attached is a screenshot where you can see the top blue circle is filled in completely with the +1 added to the script while the bottom orange circle has a small green dot in the epicentre using the unmodified script.

edit: To keep consistency with UIImage I recommend changing fillPercent to fillAmount and make it a float rather than an int.

edit 2: For my use case I also needed to animate the fill amount, but the graphic wasn’t being refreshed if the value changed. Here is my revised script which accounts for all the issues mentioned in my post here.

UICircle.cs

using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
[ExecuteInEditMode]
public class UICircle : Graphic
{
    [SerializeField]
    Texture m_Texture;

    [Range(0, 1)]
    public float fillAmount;

    public bool fill = true;
    public int thickness = 5;

    [Range(0, 360)]
    public int segments = 360;

    public override Texture mainTexture
    {
        get {
            return m_Texture == null ? s_WhiteTexture : m_Texture;
        }
    }

    float oldFillAmount;

    /// <summary>
    /// Texture to be used.
    /// </summary>
    public Texture texture
    {
        get {
            return m_Texture;
        }

        set {
            if (m_Texture == value)
                return;
            m_Texture = value;
            SetVerticesDirty();
            SetMaterialDirty();
        }
    }

    void Start ()
    {
        oldFillAmount = fillAmount;
    }

    void Update ()
    {
        this.thickness = (int)Mathf.Clamp(this.thickness, 0, (rectTransform.rect.width / 2) + 1);

        if (!Mathf.Approximately(oldFillAmount, fillAmount)) {
            this.UpdateGeometry();
            oldFillAmount = fillAmount;
        }
    }

    protected UIVertex[] SetVbo (Vector2[] vertices, Vector2[] uvs)
    {
        UIVertex[] vbo = new UIVertex[4];

        for (int i = 0; i < vertices.Length; i++) {
            var vert = UIVertex.simpleVert;
            vert.color = color;
            vert.position = vertices[i];
            vert.uv0 = uvs[i];
            vbo[i] = vert;
        }

        return vbo;
    }

    //    protected override void OnFillVBO(List<UIVertex> vbo)
    protected override void OnPopulateMesh (Mesh toFill)
    {
        float outer = -rectTransform.pivot.x * rectTransform.rect.width;
        float inner = -rectTransform.pivot.x * rectTransform.rect.width + this.thickness;
        //        vbo.Clear();
        toFill.Clear();
        var vbo = new VertexHelper(toFill);
        UIVertex vert = UIVertex.simpleVert;

        Vector2 prevX = Vector2.zero;
        Vector2 prevY = Vector2.zero;

        Vector2 uv0 = new Vector2(0, 0);
        Vector2 uv1 = new Vector2(0, 1);
        Vector2 uv2 = new Vector2(1, 1);
        Vector2 uv3 = new Vector2(1, 0);

        Vector2 pos0;
        Vector2 pos1;
        Vector2 pos2;
        Vector2 pos3;

        float degrees = 360f / segments;
        int fa = (int)((segments + 1) * this.fillAmount);

        for (int i = 0; i < fa; i++) {
            float rad = Mathf.Deg2Rad * (i * degrees);
            float c = Mathf.Cos(rad);
            float s = Mathf.Sin(rad);
            float x = outer * c;
            float y = inner * c;

            uv0 = new Vector2(0, 1);
            uv1 = new Vector2(1, 1);
            uv2 = new Vector2(1, 0);
            uv3 = new Vector2(0, 0);

            pos0 = prevX;
            pos1 = new Vector2(outer * c, outer * s);

            if (fill) {
                pos2 = Vector2.zero;
                pos3 = Vector2.zero;
            } else {
                pos2 = new Vector2(inner * c, inner * s);
                pos3 = prevY;
            }

            prevX = pos1;
            prevY = pos2;

            vbo.AddUIVertexQuad(SetVbo(new[] { pos0, pos1, pos2, pos3 }, new[] { uv0, uv1, uv2, uv3 }));
        }

        if (vbo.currentVertCount > 3) {
            vbo.FillMesh(toFill);
        }
    }
}

1 Like