【问题标题】:Why is my bitmap scaling changes when I set the PictureBox's BorderStyle to FixedSingle?为什么当我将 PictureBox 的 BorderStyle 设置为 FixedSingle 时,我的位图缩放比例会发生变化?
【发布时间】:2012-06-13 06:47:22
【问题描述】:

我有一个大小为 1000、20 的 PictureBox,我在 Form_Load 事件中设置它的位图:

void Form1_Load ( object sender, EventArgs e )
{
    SetProgressBar ( pictureBox1, 25 );
}

void SetProgressBar ( PictureBox pb, int progress )
{
    Bitmap bmp = new Bitmap ( 100, 1 );

    using ( Graphics gfx = Graphics.FromImage ( bmp ) )
    using ( SolidBrush brush = new SolidBrush ( System.Drawing.SystemColors.ButtonShadow ) )
    {
        gfx.FillRectangle ( brush, 0, 0, 100, 1 );
    }

    for ( int i = 0; i < progress; ++i )
    {
        bmp.SetPixel ( i, 0, Color.DeepSkyBlue );
    }

    // If I don't set the resize bitmap size to height * 2, then it doesn't fill the whole image for some reason.
    pb.Image = ResizeBitmap ( bmp, pb.Width, pb.Height * 2, progress );
}

public Bitmap ResizeBitmap ( Bitmap b, int nWidth, int nHeight, int progress )
{
    Bitmap result = new Bitmap ( nWidth, nHeight );

    StringFormat sf = new StringFormat ( );
    sf.Alignment = StringAlignment.Center;
    sf.LineAlignment = StringAlignment.Center;
    Font font = new Font ( FontFamily.GenericSansSerif, 10, FontStyle.Regular );

    using ( Graphics g = Graphics.FromImage ( ( Image ) result ) )
    {
            // 20 is the height of the picturebox
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
        g.DrawImage ( b, 0, 0, nWidth, nHeight );
        g.DrawString ( progress.ToString ( ), font, Brushes.White, new RectangleF ( 0, -1, nWidth, 20 ), sf );
    }
    return result;
}

在我将 BorderStyle 设置为 FlatSingle 之前,一切看起来都很棒。它在最后创造了一个差距。我该如何解决这个问题,让它看起来仍然是全彩色的?

编辑:这是它的外观:

【问题讨论】:

  • 为什么会有height*2 以及-118 是从哪里来的?这样的事情值得评论。在实际代码中,尤其是在问题中。
  • 我为两者都添加了 cmets。如果没有高度*2,它只会垂直填充一半的图片框。不知道为什么会这样。

标签: c# .net winforms drawing gdi


【解决方案1】:

似乎添加边框会增加图片框的大小。我将您的示例设置为 BorderStyle 设置为 FixedSingle、None 和 Fixed3D,每个结果都不同。这些 PictureBox 中的每一个都从相同的位置开始,您可以看到可见宽度实际上已经改变。

FixedSingle 大约是 4 像素,Fixed3D 大约是 2 像素。我不确定幕后发生了什么,但您应该能够像这样围绕它进行编码。

 if (pb.BorderStyle == BorderStyle.FixedSingle)
     pb.Image = ResizeBitmap(bmp, pb.Width + 4, pb.Height * 2, progress);
 else if (pb.BorderStyle == BorderStyle.Fixed3D)
     pb.Image = ResizeBitmap(bmp, pb.Width + 2, pb.Height * 2, progress);
 else 
     pb.Image = ResizeBitmap(bmp, pb.Width, pb.Height * 2, progress);

这给出了如下所示的结果。


如果您查看DisplayRectangle 属性,您会发现您的客户矩形在您更改边框样式时正在发生变化:

BorderStyle.None = 1000 像素
BorderStyle.Fixed3D = 996 像素
BorderStyle.FixedSingle = 998 像素

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2013-07-30
    • 2021-09-24
    • 2011-04-16
    相关资源
    最近更新 更多