我试图理解图形,在 Graphics.FromImage 文档中,它有这样的示例:
private void FromImageImage(PaintEventArgs e)
{
// Create image.
Image imageFile = Image.FromFile("SampImag.jpg");
// Create graphics object for alteration.
Graphics newGraphics = Graphics.FromImage(imageFile);
// Alter image.
newGraphics.FillRectangle(new SolidBrush(Color.Black), 100, 50, 100, 100);
// Draw image to screen.
e.Graphics.DrawImage(imageFile, new PointF(0.0F, 0.0F));
// Dispose of graphics object.
newGraphics.Dispose();
}
我是 C# 和 Windows 窗体的新手,正在努力理解这一切是如何组合在一起的。这段代码是如何运行的,比如当表单首次加载或按下按钮时?
也许这会有所帮助。我有一个两者都借鉴的例子Paint
事件,而且还借鉴了现有的Image
。我创建了一个带有两个图片框的表单。每种情况一个。pictureBox1
有一个事件处理程序.Paint
事件,同时pictureBox2
仅在按下按钮时绘制。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
pictureBox1.BackColor=Color.Black;
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
// The code below will draw on the surface of pictureBox1
// It gets triggered automatically by Windows, or by
// calling .Invalidate() or .Refresh() on the picture box.
DrawGraphics(e.Graphics, pictureBox1.ClientRectangle);
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
// The code below will draw on an existing image shown in pictureBox2
var img = new Bitmap(pictureBox2.Image);
var g = Graphics.FromImage(img);
DrawGraphics(g, pictureBox2.ClientRectangle);
pictureBox2.Image=img;
}
void DrawGraphics(Graphics g, Rectangle target)
{
// draw a red rectangle around the moon
g.DrawRectangle(Pens.Red, 130, 69, 8, 8);
}
}
因此,当您启动应用程序时,红色矩形仅出现在左侧,因为尚未按下按钮。
当按下按钮时,红色矩形出现在显示的图像顶部pictureBox2
.
没什么戏剧性的,但它确实完成了工作。因此,根据您需要的操作模式(用户图形或图像注释),使用示例代码来了解如何操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)