我只想在winforms中的文本框或标签中添加一些文本,然后将该文本另存为jpeg / bmp等图像。这可能吗?
答案 0 :(得分:1)
使用此代码,您可以创建任何给定控件的屏幕截图。在这种文本框或标签的情况下:
private Bitmap CaptureControl(Control ctl)
{
Rectangle rect;
if (ctl is Form)
rect = new Rectangle(ctl.Location, ctl.Size);
else
rect = new Rectangle(ctl.PointToScreen(new Point(0, 0)), ctl.Size);
Bitmap bitmap = new Bitmap(rect.Width, rect.Height, PixelFormat.Format64bppPArgb);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bitmap.Size, CopyPixelOperation.SourceCopy);
}
return bitmap;
}
答案 1 :(得分:1)
DrawToBitmap课程的Control方法可以帮助您:
var bitmap = new Bitmap(this.textbox.Width, this.textbox.Height);
this.textbox.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
请注意,您将拥有文本框的完整外观:边框,背景颜色等
答案 2 :(得分:0)
您可以使用Graphics类将文本绘制到新的Bitmap对象上。 下面的脚本将Bitmap转换为Image对象,然后您可以将其应用于某个地方,或保存到磁盘。
// Our text to paint
String str = "This is my text.";
// Create our new bitmap object
Bitmap bmp = new Bitmap(128, 128);
Image img = Image.FromHbitmap(bmp.GetHbitmap());
// Get our graphics object
Graphics g = Graphics.FromImage(img);
g.Clear(Color.White);
// Define our image padding
var imgPadding = new Rectangle(2, 2, 2, 2);
// Determine the size of our text, using our specified font.
Font ourFont = new Font(
FontFamily.GenericSansSerif,
12.0f,
FontStyle.Regular,
GraphicsUnit.Point
);
SizeF strSize = g.MeasureString(
str,
ourFont,
(bmp.Width - imgPadding.Left - imgPadding.Right),
StringFormat.GenericDefault
);
// Create our brushes
SolidBrush textBrush = new SolidBrush(Color.DodgerBlue);
// Draw our string to the bitmap using our graphics object
g.DrawString(str, ourFont, textBrush, imgPadding.Left, imgPadding.Top);
// Flush
g.Flush(System.Drawing.Drawing2D.FlushIntention.Sync);
// Save our image.
img.Save("myImage.png", System.Drawing.Imaging.ImageFormat.Png);
// Clean up
textBrush.Dispose();
g.Dispose();
bmp.Dispose();
希望这有帮助。