Home > Net >  Draw vertical lines on surface of the circle
Draw vertical lines on surface of the circle

Time:11-28

I draw geometric shapes using skiasharp. They are mostly circles. If we have simple example, just like this:

using System;
using SkiaSharp;

void Draw(SKCanvas canvas, int width, int height)
{
    
        var circleBorder = new SKPaint
        {
            IsAntialias = true,
            Style = SKPaintStyle.Stroke,
            Color = SKColors.Blue,
            StrokeWidth = 5
        };
        canvas.DrawCircle(width / 2, height / 2, 30, circleBorder);
}

we get a simple cirle. I've looked at the skiasharp documentation and still haven't found a way to draw lines over the surface of a circle. Can anyone suggest how to add those lines. I am sending an example of a picture of what I need to draw. Any help is appreciated.

vertical lines on surface of the circle

CodePudding user response:

Based on your description I'd go with something based on circle equation:

void Draw(SKCanvas canvas, int width, int height)
{
    var circleBorder = new SKPaint
    {
        IsAntialias = true,
        Style = SKPaintStyle.Stroke,
        Color = SKColors.Blue,
        StrokeWidth = 5
    };

    var radius = 30f;
    var cx = width / 2f;
    var cy = height / 2;

    // define x-wise range on circle where we want to draw lines
    // 0 means leftmost point, 1 - rightmost
    // 0 <= startX < endX <= 1
    var startX = 0.15f;
    var endX = 1f;
    // how many lines in above range
    var count = 4;
    // length of lines
    var lineLength = 40f;

    var step = (endX - startX) / (count - 1);

    for (var i = 0; i < count; i  )
    {
        // R^2 = (x-x0)^2   (y-y0)^2 => sqrt(R^2 - (x-x0)^2) = |y-y0|
        // we consider here coords from perspective where (0,0) is the leftmost point on the circle
        // therefore x0 = radius, y0 = 0

        var x = (i * step   startX) * radius * 2f; // current x on circle
        var absy_y0 = MathF.Sqrt(2 * x * radius - x * x); // == MathF.Sqrt(radius * radius - (x - radius) * (x - radius));
        var y = -Math.Abs(absy_y0); // we want lines upwards so only care about the smaller solution to equation

        canvas.DrawLine(x   cx - radius, y   cy, x   cx - radius, y   cy - lineLength, circleBorder);
    }

    canvas.DrawCircle(cx, cy, radius, circleBorder);
}

You can parametrize the hardcoded values however you want. Result of the above code:

enter image description here

  • Related