C# 调整图片框生成图像的大小
本文关键字:图像 调整 | 更新日期: 2023-09-27 18:33:19
我根据文本绘制图像(_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)。
目标是基于文本字符串制作图像,我还希望能够更新字符串并重新绘制更新的字符串。
提前非常感谢!
设置图像的新大小解决了我的问题。
base.Image = newImage; //old image size(100,20) - newImage size(150, 20)
base.Size = new Size(newImage.Width, newImage.Height);
base.Refresh(); //forces redraw