Search code examples
f#imagesharp

F# call .Net Function with generic params - wont compile


F# Beginner here, I want to draw a Polygon using ImageSharp. The build fails with:

No overloads match for method 'DrawPolygon'. The available overloads are shown below. error FS0001: This expression was expected to have type 'Image' but here has type 'a * 'b'.

    let renderRect(img:Image<Rgba32>) =

        let points: PointF list = [
            new PointF(float32 2.0, float32 8.0);
            new PointF(float32 4.0, float32 1.0);
            new PointF(float32 1.0, float32 7.0);
            new PointF(float32 5.0, float32 2.0);
        ]

        img.Mutate (fun x -> x.DrawPolygon(Rgba32.White, 1.0, points))
        img

The signature of the method i want to call:

static IImageProcessingContext<TPixel> DrawPolygon<TPixel>(this IImageProcessingContext<TPixel> source, TPixel color, float thickness, params PointF[] points) where TPixel : struct, IPixel<TPixel>

Solution

  • I see several issues:

    1. As Aaron said, you're passing a list where an array is required.
    2. The second argument to DrawPolygon should be a float32, not a float. Note that rather than calling the float32 function, you can just use a literal of the correct type by adding a suffix: 1.0f.
    3. The second argument to Mutate needs to be an Action<_>, so it shouldn't return anything; this means you should ignore the result of the DrawPolygon call rather than returning it. You can achieve this by putting |> ignore after the call.

    Here's a version of your code with these issues addressed:

    let renderRect(img:Image<Rgba32>) =
    
        let points = [|
            PointF(2.0f, 8.0f);
            PointF(4.0f, 1.0f);
            PointF(1.0f, 7.0f);
            PointF(5.0f, 2.0f);
        |]
    
        img.Mutate (fun x -> x.DrawPolygon(Rgba32.White, 1.0f, points) |> ignore)
        img
    

    Since you didn't include a full repro (or even the list of suggested overloads from the error message!) it's hard to know if there's anything else that needs to be changed.