Search code examples
c#monogtkcairogdk

Fill a rectangle with a larger image with Cairo


I'm developing an application in C# with GTk. In this application I have to display boxes. Some are filled with color and others with an image. These boxes are resizable and movable. Boxes are displayed in a DrawingArea.

When I draw an image with Cairo context the image doesn't fill the box entirely if the image is larger than the box. I have tried some solutions like using ScaleSimple method on the Pixbuf every time the box is resized, but when the box is large the application become slow. And create a new Pixbuf instance everytime is not a good approach since performance is important for my application.

I have searched in the documentation and internet if there is a parameter to tell Cairo to fill the rectangle with the image but I had found nothing.

Here is my code to draw the image :

context.Translate(Bounds.X, Bounds.Y);
CairoHelper.SetSourcePixbuf(context, _source.Buffer, 0.0d, 0.0d);
context.Rectangle(0.0d, 0.0d, Bounds.Width, Bounds.Height);
context.Fill();

Bounds is a Gdk.Rectangle and _source.Buffer a Pixbuf instance.

Thanks for the help.


Solution

  • Finally found a solution.

    Just need to scale before painting the image. Like that, the image will always be the same size as a defined rectangle.

    float xScale = (float)rectangle.Width / (float)buffer.Width;
    float yScale = (float)rectangle.Height / (float)buffer.Height;
    context.Translate(rectangle.X, rectangle.Y);
    context.Scale(xScale, yScale);
    
    CairoHelper.SetSourcePixbuf(context, buffer, 0.0d, 0.0d);
    context.Paint();
    

    The variable named buffer is a Pixbuf instance. With this solution, there is no need to recreate the Pixbuf by using ScaleSimple, and the application doesn't slow down.