I get unexpected results from Graphics.DrawImage

To reproduce this problem, create a 2x2 black and white image in Microsoft Paint saved as D:\small.png. Then create a new WinForms application in Visual Studio with a borderless PictureBox. Then use the following code:

void f6(Graphics g)
{
    var img = Image.FromFile(@"d:\small3.png");
    var srcRect = new Rectangle(0, 0, img.Width, img.Height);
    int factor = 400;
    var destRect = new Rectangle(0, 0, img.Width * factor, img.Height * factor);
    g.DrawRectangle(new Pen(Color.Blue), destRect);
    g.DrawImage(img, destRect, srcRect, GraphicsUnit.Pixel);
}

void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    f6(e.Graphics);
}

I expect the entire rectangle inside the blue margins to turn black and the output will be as follows:

enter image description here

Why is this happening?


OK thanks. I do not know about interpolation. now change the code as follows:

void f6(Graphics g)
{
    var img = Image.FromFile(@"d:\small3.png");
    var srcRect = new Rectangle(0, 0, img.Width, img.Height);
    int factor = 200;
    var destRect = new Rectangle(0, 0, img.Width * factor, img.Height * factor);
    g.FillRectangle(new SolidBrush(Color.DarkCyan), pictureBox1.ClientRectangle);
    g.InterpolationMode = InterpolationMode.NearestNeighbor;
    g.DrawRectangle(new Pen(Color.Blue), destRect);
    g.DrawImage(img, destRect, srcRect, GraphicsUnit.Pixel);
}

it produces the following result:

Result3

- . 6060 . , 2x2. . , GDI + destRect srcRect?! , , . , , . ++ StretchBlt . .

+3
2

GDI + .

(0,0) . (-1, -1) .

, (-0,5, -0,5) (0,5,0,5), - (-1,5, -1,5) ( -0,5, -0,5). , 0,5 .

, (-0,5, -0,5, img.Width, img.Height).

, PixelOffsetMode, . , , .

+5

, . 16 , 4 , 12 , .

. InterpolationMode Graphics g InterpolationMode.NearestNeighbor:

void f6(Graphics g) 
{ 
    var img = Image.FromFile(@"d:\small3.png"); 
    var srcRect = new Rectangle(0, 0, img.Width, img.Height); 
    int factor = 400; 
    var destRect = new Rectangle(0, 0, img.Width * factor, img.Height * factor);
    g.ImterpolatonMode = InterpolationMode.NearestNeighbor;
    g.DrawRectangle(new Pen(Color.Blue), destRect); 
    g.DrawImage(img, destRect, srcRect, GraphicsUnit.Pixel); 
} 
+4

All Articles