Eto.Drawing.Graphics Slow - Clear() or FillRectangle()

I am trying to create color swatches for each layer. I will use them in nodes of a TreeGridView. For some reason code below takes few seconds to execute. Slowdown is at the Clear() or FillRectangle() methods. Any idea why? Is there a better way to do this?

import Eto.Drawing as drawing
import Eto.Forms as forms

def Swatch(color=(250, 200, 100)):
    size = drawing.Size(10, 10) * int(forms.Screen.PrimaryScreen.LogicalPixelSize)
    bitmap = drawing.Bitmap(size, drawing.PixelFormat.Format32bppRgb)

    with drawing.Graphics(bitmap) as g:
        #g.Clear(drawing.Color.FromArgb(color[0], color[1], color[2])) #even slower
        rec = drawing.Rectangle(drawing.Point(1, 1), drawing.Size(8, 8))
        col = drawing.Color.FromArgb(color[0], color[1], color[2])
        g.FillRectangle(col, rec)

    return bitmap

for i in range(50):
    Swatch()

Hi @spineribjoint1,

I did something very similar for my own layerPanel, you can create and fill the bitmap all in one step, which in my case worked quite fast. Here is the original source code in c#:

            // Color
            var bitmapSize = Settings.LayerPanelColorBitmapSize;
            Grid.Columns.Add(new GridColumn
            {
                DataCell = new ImageViewCell { Binding = Binding.Property<Layer, Image>(l => new Bitmap(bitmapSize, bitmapSize, PixelFormat.Format24bppRgb, from index in Enumerable.Repeat(0, bitmapSize * bitmapSize) select l.Color.ToEto()))},
                HeaderText = "Color",
                Editable = true
            });

The basic idea is to supply a list of colors while creating the bitmap, so all pixels are set to the right color right away.

Even more optimised would be to first store all colors in a dictionary, so only one bitmap for every different color has to be genrated (as black is the default new layer color there can be maaany of those)

I have not tried this in python, if you post a more complete example of your actual UI i can try to translate the c#

Hope to help

Thank you @lando.schumpich. I missed the bitmap class methods. SetPixel() made the function instant. Python code is bellow.

def Swatch(color=(250,200,100)):
    bitmap = drawing.Bitmap(10, 10, drawing.PixelFormat.Format32bppRgb)
    col = drawing.Color.FromArgb(color[0], color[1], color[2])
    width = 10; height = 10
    for x in range(1, width - 1):
        for y in range(1, height - 1):
            bitmap.SetPixel(x, y, col)
    return bitmap