Search code examples
xamarinxamarin.formsskiaskiasharp

SkiaSharp does not fill triangle with StrokeAndFill


I am trying to draw and fill a triangle. I referred an android - question How to draw filled triangle on android Canvas and did the following. It draws the triangle but it doesn’t fill it. How to get it filled? Also, is it possible to get it filled with a different color than the line color?

Xamarin Forms

private void OnPainting(object sender, SKPaintSurfaceEventArgs e)
{
        var surface = e.Surface;
        var canvas = surface.Canvas;
        canvas.Clear(SKColors.White);


        var pathStroke2 = new SKPaint
        {
            IsAntialias = true,
            Style = SKPaintStyle.StrokeAndFill,
            Color = new SKColor(244, 0, 110, 200),
            StrokeWidth = 5
        };

        var path2 = new SKPath { FillType = SKPathFillType.EvenOdd };
        path2.MoveTo(0, 0);
        path2.LineTo(0, 140);
        path2.MoveTo(0, 140);
        path2.LineTo(140, 140);
        path2.MoveTo(140, 140);
        path2.LineTo(0, 0);
        path2.Close();
        canvas.DrawPath(path2, pathStroke2);

    }

enter image description here


Solution

  • you don't need to use both LineTo() and MoveTo() - I suspect doing so is breaking the fill algorithm. Instead, just use

    path2.MoveTo(0, 0);
    path2.LineTo(0, 140);
    path2.LineTo(140, 140);
    path2.LineTo(0, 0);
    path2.Close();