3

鉴于 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函数?

4

3 回答 3

8

从这样的绘画事件中

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) ;
}
于 2012-08-01T06:03:07.997 回答
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. 在窗体的Graphics -Object上绘制一个填充的矩形,颜色为 0,0,大小为 100,100
于 2012-08-01T06:12:58.043 回答
0

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

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

于 2016-06-24T14:41:28.890 回答