WriteableBitmapEx icon indicating copy to clipboard operation
WriteableBitmapEx copied to clipboard

Avoid allocation of unnecessary objects

Open zgabi opened this issue 3 years ago • 1 comments

For example BitmapContext

The public static void DrawLine(this WriteableBitmap bmp, int x1, int y1, int x2, int y2, int color, Rect? clipRect = null) method simply calls the public static void DrawLine(BitmapContext context, int pixelWidth, int pixelHeight, int x1, int y1, int x2, int y2, int color, Rect? clipRect = null) method. Which is public, so the user can directyl call it:


            using (var context = bmp.GetBitmapContext())
            {
                WriteableBitmapExtensions.DrawLine(context, context.Width, context.Height, 10, 20, 100, 300, red);
            }

But the other Draw/Fill methods are not following the same logic. It would be good to have a DrawXxx(BitmapContext ...) method for all draw/fill methods. And the WriteableBitmap extension method should create the context, and call the new method whihc receives the context.

It would be event more better if this method will be the extension (non-extesion) method of the BitmapContext. So the user could write:

            using (var context = bmp.GetBitmapContext())
            {
                context.DrawLine(context.Width, context.Height, 10, 20, 100, 300, red);
                context.FillPolygon(points, green);
            }

Other improvemetns: It would be good to allow to pass Spans to the methods instead of arrays:

Instead of this: public static void FillPolygon(this WriteableBitmap bmp, int[] points, Color color) the following: public static void FillPolygon(this WriteableBitmap bmp, Span<int> points, Color color)

So the users do not have to create the exact size array, the could use a larger buffer and pass the part of it.

More improvements: Do not allocate new arrays in the draw/fill methods. Use stackalloc instead. (if the array size is smaller than a limit)

zgabi avatar Jun 30 '22 18:06 zgabi

Great feedback. Thank you. At the time the library was created there was no Span and alike. ;-) We accept pull request, so if you want to propose some of your changes in a PR that would be good.

reneschulte avatar Jul 01 '22 07:07 reneschulte