1

在以下代码中:

void f10(Graphics g)
{
    var img = new Bitmap(1, 1);
    img.SetPixel(0, 0, Color.Black);
    var destRect = pictureBox1.ClientRectangle;
    destRect.Inflate(-5, -5);
    g.DrawRectangle(new Pen(Color.Blue), destRect);
    var srcRect = new RectangleF(-.5f, -.5f, img.Width, img.Height);
    g.InterpolationMode = InterpolationMode.NearestNeighbor;
    g.DrawImage(img, destRect, srcRect, GraphicsUnit.Pixel);
}

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

private void pictureBox1_Resize(object sender, EventArgs e)
{
    textBox1.Text = pictureBox1.ClientSize.Width + "x" + pictureBox1.ClientSize.Height;
    pictureBox1.Invalidate();
}

我得到以下结果:

结果 http://www.uploadup.com/di-XJ2I.png

该表单包含一个适合整个表单内部内容的图片框和一个显示图片框尺寸的文本框。我希望黑盒子的右侧适合蓝色矩形的整个内部。为什么没有?!

差距 http://www.uploadup.com/di-YGWL.png

通过更改尺寸值(调整图片框的大小),间隙会发生变化。


我使用以下代码根据图像宽度值查找错误的偏移量:

void f11(Graphics g)
{
    var img = new Bitmap(1, 1);
    img.SetPixel(0, 0, Color.Black);
    var bmp = new Bitmap(10010, 6);
    var destRect = new Rectangle(0, 0, 3, bmp.Height);
    var bmpG = Graphics.FromImage(bmp);
    var srcRect = new RectangleF(-.5f, -.5f, img.Width, img.Height);
    bmpG.InterpolationMode = InterpolationMode.NearestNeighbor;
    g.DrawString("Please Wait...", SystemFonts.DefaultFont, Brushes.Black, 10, 10);
    for (; destRect.Width < bmp.Width; destRect.Width++)
    {
        bmpG.DrawRectangle(new Pen(Color.Blue), new Rectangle(destRect.X, destRect.Y, destRect.Width-1, destRect.Height-1));
        bmpG.DrawImage(img, new Rectangle(destRect.X+1, destRect.Y+1, destRect.Width-2, destRect.Height-2), srcRect, GraphicsUnit.Pixel);
        //g.FillRectangle(new SolidBrush(bmp.GetPixel(destRect.Width-2, 1)), pictureBox1.ClientRectangle);
        int n = 0;
        while (!bmp.GetPixel(destRect.Width - 2 - n, 1).ToArgb().Equals(Color.Black.ToArgb())) n++;
        Console.WriteLine("{0}\t{1}", destRect.Width-2, n);
    }
    g.FillRectangle(new SolidBrush(pictureBox1.BackColor), pictureBox1.ClientRectangle);
    g.DrawString("Done.", SystemFonts.DefaultFont, Brushes.Black, 10, 10);
}

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

结果是:

结果

你能帮我找到解决方法吗?谢谢

4

0 回答 0