C#调整图片框生成的图像

时间:2014-12-05 16:05:26

标签: c# graphics picturebox onpaint

我根据文字(_label)绘制图像

public Image getImage()
    {

        PointF initialLocation = new PointF(0.1f, 0.1f);
        //Bitmap b = new Bitmap(130, 50);

        Graphics g = Graphics.FromImage(new Bitmap(1,1));
        System.Drawing.Font font = new System.Drawing.Font("Arial", 16, FontStyle.Regular);
        SizeF bounds = g.MeasureString(_label, font, new PointF(0,0), new StringFormat(StringFormatFlags.MeasureTrailingSpaces));

        Bitmap b = new Bitmap((int)bounds.Width, (int)bounds.Height);

        //b.MakeTransparent();
        using (Graphics graphics = Graphics.FromImage(b))
        {
            //using (Font arialFont = new Font("Arial", 16))
            {
                graphics.DrawString(_label, font, Brushes.White, initialLocation);
            }
        }

        Image image = b;
        return image;
    }

这会将图像绘制为文本占用时间的大小。例如,在这种情况下,“LabelTest”将是Image.Width = 103和Image.Height = 26.我还希望能够更新(设置)文本并在屏幕上更新它。当我将文本更改为“LabelTest123456789”并再次调用getImage()方法时,Image.Width更改为213.

在父类中,我然后设置上面提到的PictureBox图像:

public partial class Widget : System.Windows.Forms.PictureBox

.. .. ..

else if (t == Widget.WidgetType.LABEL)
        {

            **base.Image = image;**
            base.BackColor = Color.Transparent;
        }

然后调用onPaint方法在屏幕上绘制它:

protected override void OnPaint(PaintEventArgs pe)
    {
        base.OnPaint(pe);
    }

在这个'onPaint'方法中,ClipRectangle的值仍然具有从第一次设置时的大小属性(103,26),我希望这个使用新的大小(213,26)。

目标是基于一串文本制作图像,我还希望能够更新字符串并重新绘制更新后的字符串。

非常感谢提前!

1 个答案:

答案 0 :(得分:0)

设置图像的新尺寸已解决了我的问题。

base.Image = newImage; //old image size(100,20) - newImage size(150, 20)
base.Size = new Size(newImage.Width, newImage.Height);
base.Refresh(); //forces redraw
相关问题