简体   繁体   English

在Graphics.Drawing中使用未分配的局部变量

[英]Use of Unassigned Local Variable with Graphics.Drawing

So I'm trying to write a program that draws a circle by drawing a line every 1 degree and changes color by incrementing through RGB (Started by Random). 因此,我正在尝试编写一个程序,该程序通过每1度画一条线来画一个圆,并通过增加RGB(由Random启动)来改变颜色。

Here is the code that I have so far 这是我到目前为止的代码

public static void drawCircle(int iRandR, int iRandG, int iRandB)
{
    for (int x = 0; x < 359; ++x)
    {
        double dXAngle = 0;
        double dYAngle = 0;
        dXAngle = 300 + Math.Cos(x) + 200;
        dYAngle = 300 + Math.Sin(x) + 200;
        Pen pPen = new Pen(Color.FromArgb(255, iRandR, iRandG, iRandB));
        Graphics gDraw;
        int iXAngle = Convert.ToInt32(dXAngle);
        int iYAngle = Convert.ToInt32(dYAngle);
        gDraw.DrawLine(pPen, 300, 300, iXAngle, iYAngle); //Error called here
    }

}
private void drawCircleButton_Click(object sender, EventArgs e)
{
    int genRandR = 0;
    int genRandG = 0;
    int genRandB = 0;
    Random rRand = new Random();
    genRandR = rRand.Next(0, 255);
    genRandG = rRand.Next(0, 255);
    genRandB = rRand.Next(0, 255);
    drawCircle(genRandR, genRandG, genRandB);
    drawCircleButton.Hide();
}

The only problem is that the compiler has a problem with the above line and it throws "Use of unassigned local variable 'gDraw'" I did some googling and a lot of other examples looked like mine but I can't figure out why mine was throwing this error. 唯一的问题是编译器在上述行中有问题,并且抛出“使用未分配的局部变量'gDraw'”的问题,我做了一些谷歌搜索,还有许多其他示例看起来像我的,但我不知道为什么我的是抛出此错误。

Any help would be greatly appreciated. 任何帮助将不胜感激。

You need to pass the desired Graphics instance as a parameter from somewhere. 您需要从某个地方传递所需的Graphics实例作为参数。 The Graphics class, as explained on MSDN, encapsulates a GDI+ drawing surface. 如MSDN上所述, Graphics类封装了GDI +绘图表面。 It's used to abstract various drawing operations to different display devices (your screen, a bitmap, metafile, or even printing). 它用于将各种绘图操作抽象到不同的显示设备(您的屏幕,位图,图元文件,甚至是打印)。

public static void DrawCircle(Graphics gDraw, int iRandR, int iRandG, int iRandB)
{
    ...
}

You are probably calling it from a Paint event handler, or something similar, where you have access to the Graphics object you want to draw to. 您可能是从Paint事件处理程序或类似的东西调用它的,您可以在其中访问要绘制到的Graphics对象。 Ie: 即:

protected override void OnPaint(PaintEventArgs p)
{
     var graphics = p.Graphics;
     DrawCircle(graphics, ...);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM