How to draw a circle in a custom control using Vector Graphic?

Hello everyone,

I’m currently trying to draw a circle using the Vector Graphic library. And it’s not quite pretty neither simple.

8909508--1219827--upload_2023-3-28_17-52-47.png

I don’t want to use the Unity’s RadialProgress example because it generates a mesh ; I want to do that with svg. I found that VisualElements have an event generateVisualContent. So, I subscribe to it and when my element is renderer, I create a shape that I fill with the VectorUtils.MakeCircleShape method. But when I draw the contours, it seems broken.

private void OnGenerateVisualContent(MeshGenerationContext context)
        {
            var center = new Vector2(
                context.visualElement.resolvedStyle.width / 2,
                context.visualElement.resolvedStyle.height / 2);
           
            Shape shape = new();
            VectorUtils.MakeCircleShape(shape, center, 100);

            var paint2D = context.painter2D;
            paint2D.strokeColor = Color.black;
            paint2D.fillColor = Color.yellow;

            foreach (var contour in shape.Contours)
            {
                paint2D.BeginPath();
                foreach (var segment in contour.Segments)
                    paint2D.BezierCurveTo(segment.P0, segment.P1, segment.P2);
                paint2D.ClosePath();
            }

            paint2D.Fill();
            paint2D.Stroke();
        }

I know that Vector Graphics are still on the UITK roadmap, but I want to know if someone has already tried to draw simple elements using this package and UITK. Also, it seems weird that there are no methods to draw simple shapes by using the painter2D ; maybe I’m using it badly?

Thank you :slight_smile:

Try this: painter2D.Arc(center, radius, 0, Angle.FromDegrees(360), ArcDirection.Clockwise);

1 Like

Thank you! It works pretty well for a simple circle or arc draw. But is there an option to change the fill mode like VectorGraphics does?
8911414--1220272--upload_2023-3-29_12-35-3.png

You can subtract the inside by adding another circle with a different direction:

p.BeginPath();
p.Arc(new Vector2(50, 50), 50, 0, Angle.Degrees(360), ArcDirection.Clockwise);
p.Arc(new Vector2(50, 50), 25, 0, Angle.Degrees(360), ArcDirection.CounterClockwise);
p.fillColor = Color.red;
p.Fill();

If you want to change the winding order of the fill mode, you can specify it as an argument to Fill():

Also I just found out that we have a page of the manual that explains how to create a progress bar with the Painter 2D:

2 Likes

Ok! Really great to see that. Thank you for your answers!

1 Like