如何使用PaintEventArgs参数调用函数?

时间:2012-08-01 05:59:30

标签: c# .net

鉴于MSDN中的以下代码示例:

private void GetPixel_Example(PaintEventArgs e)
    {

        // Create a Bitmap object from an image file.
        Bitmap myBitmap = new Bitmap(@"C:\Users\tanyalebershtein\Desktop\Sample Pictures\Tulips.jpg");

        // Get the color of a pixel within myBitmap.
        Color pixelColor = myBitmap.GetPixel(50, 50);

        // Fill a rectangle with pixelColor.
        SolidBrush pixelBrush = new SolidBrush(pixelColor);
        e.Graphics.FillRectangle(pixelBrush, 0, 0, 100, 100);
    }

如何调用Paint函数?

3 个答案:

答案 0 :(得分:6)

来自paint事件的

就像这样

private PictureBox pictureBox1 = new PictureBox();

pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);

private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
   GetPixel_Example(e) ;
}

答案 1 :(得分:1)

您可以从表单的PaintEvent中调用此方法,例如

public class Form1 : Form
{
    public Form1()
    {
        this.Paint += new PaintEventHandler(Form1_Paint);
    }

    //....

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        GetPixel_Example(e);
    }

    private void GetPixel_Example(PaintEventArgs e)
    {
        // Create a Bitmap object from an image file.
        Bitmap myBitmap = new Bitmap(@"C:\Users\tanyalebershtein\Desktop\Sample Pictures\Tulips.jpg");

        // Get the color of a pixel within myBitmap.
        Color pixelColor = myBitmap.GetPixel(50, 50);

        // Fill a rectangle with pixelColor.
        SolidBrush pixelBrush = new SolidBrush(pixelColor);
        e.Graphics.FillRectangle(pixelBrush, 0, 0, 100, 100);
    }
}
  1. 加载图片
  2. 在x = 50,y = 50
  3. 时获取像素的颜色
  4. 绘制一个填充矩形,其颜色为0,0,大小为100,100 在Graphics - 表单
  5. 的对象上

答案 2 :(得分:0)

您不应该自己调用Paint方法。只要需要绘制组件,.NET框架就会调用Paint方法。这通常在窗口移动,最小化等时发生。

如果您想告诉.NET框架重新绘制您的组件,请在组件或其父组件上调用Refresh()