Fill a rectangle with an image using Mono Cairo Library

782 Views Asked by At

I am trying to fill an image inside a rectangle. I was able to set the image position correctly to the leftmost corner of the rectangle. However the scaling does not work as expected. Any help on this is appreciated. Below is my code. This is a 1290*1990 dimensions image.

        Cairo.Rectangle imageRectangle = new Cairo.Rectangle(50, 100, width, height);

        ctx.NewPath();
        Cairo.ImageSurface imgSurface = new Cairo.ImageSurface("C:/Temp/Image.png");
        ctx.SetSource(imgSurface, topLeftPoint); //topLeft is (50,100)

        float xScale = (float)imageRectangle.Width / (float)imgSurface.Width;
        float yScale = (float)imageRectangle.Height / (float)imgSurface.Height;

        //Reposition the image to the rectangle origin
        ctx.Translate(imageRectangle.X, imageRectangle.Y);
        ctx.Scale(xScale, yScale);

        ctx.Paint();

Thanks!!

1

There are 1 best solutions below

0
On BEST ANSWER

I found the solution. I was setting the source at the wrong place. Below is the right code

    Cairo.Rectangle imageRectangle = new Cairo.Rectangle(50, 100, width, height);

    ctx.NewPath();
    Cairo.ImageSurface imgSurface = new Cairo.ImageSurface("C:/Temp/Image.png");


    float xScale = (float)imageRectangle.Width / (float)imgSurface.Width;
    float yScale = (float)imageRectangle.Height / (float)imgSurface.Height;

    //Reposition the image to the rectangle origin
    ctx.Translate(imageRectangle.X, imageRectangle.Y);
    ctx.Scale(xScale, yScale);

    ctx.SetSource(imgSurface); 
    ctx.Paint();

Thanks!