我怎么能笼络在C#中的面板? [英] How can I draw over a panel in C#?
问题描述
嘿,我需要做的比我在C#中,但没有将panel1_Paint里面我的绘制代码面板图,我怎么能做到这一点?
顺便说一句,我使用的WinForms
Hey, I need to do my drawing over a panel in C# but without placing my drawing code inside "panel1_Paint", how can I do that ?? BTW, I'm using WinForms.
更新:我忘了,使一些清晰的,我不需要把我的画油漆处理程序中的代码,因为我要开始绘制根据按钮的事件。
Update : I forgot to make something clear, I need not to place my drawing code inside paint handler, because I need to start drawing depending on buttons' events.
推荐答案
通常你在所有你的图纸Paint事件处理程序。如果你想要做的任何更新(如果用户单击面板为例),你可以选择推迟采取行动:你存储所需要的数据(坐标用户点击的地方),并强制控制的重绘。这会导致油漆事件被解雇,在这里你就可以得出你之前存储的东西。
Usually you do all your drawings in the paint event handler. If you want to do any update (if a user clicks on the panel for example) you have to defer that action: you store the required data (coordinates where the user clicked) and force a redraw of the control. This causes the paint event to be fired, where you can then draw things you stored before.
另一种方式是(如果你真的想以'panel1_Paint外画'事件处理),以缓冲图像内画,将图像复制到图形的绘制事件处理程序对象控件
Another way would be (if you really want to draw outside of the 'panel1_Paint' event handler) to draw inside a buffer image, and copy the image to the controls graphics object in the paint event handler.
更新:
一个例子:
public class Form1 : Form
{
private Bitmap buffer;
public Form1()
{
InitializeComponent();
// Initialize buffer
panel1_Resize(this, null);
}
private void panel1_Resize(object sender, EventArgs e)
{
// Resize the buffer, if it is growing
if (buffer == null ||
buffer.Width < panel1.Width ||
buffer.Height < panel1.Height)
{
Bitmap newBuffer = new Bitmap(panel1.Width, panel1.Height);
if (buffer != null)
using (Graphics bufferGrph = Graphics.FromImage(newBuffer))
bufferGrph.DrawImageUnscaled(buffer, Point.Empty);
buffer = newBuffer;
}
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
// Draw the buffer into the panel
e.Graphics.DrawImageUnscaled(buffer, Point.Empty);
}
private void button1_Click(object sender, EventArgs e)
{
// Draw into the buffer when button is clicked
PaintBlueRectangle();
}
private void PaintBlueRectangle()
{
// Draw blue rectangle into the buffer
using (Graphics bufferGrph = Graphics.FromImage(buffer))
{
bufferGrph.DrawRectangle(new Pen(Color.Blue, 1), 1, 1, 100, 100);
}
// Invalidate the panel. This will lead to a call of 'panel1_Paint'
panel1.Invalidate();
}
}
现在绘制的图像不会丢失,即使经过重绘控制的,因为它仅引出缓冲器(图像,保存在存储器中)。此外,您可以随时借鉴的东西一事件发生时,通过简单地画到缓冲区中。
Now the drawn images wont be lost, even after a redraw of the control, because it only draws out the buffer (the image, saved in the memory). Additionally you can draw things anytime a event occurs, by simply drawing into the buffer.
这篇关于我怎么能笼络在C#中的面板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!