【发布时间】:2015-12-02 22:43:19
【问题描述】:
所以我要做的是使用另一个组合框更改形状的颜色。所以第一个组合框表示将显示什么样的形状作为图像。例如,如果我按下三角形选项,它将显示三角形。好吧,我还有另一个组合框,它显示形状将采用哪种颜色。到目前为止,我的代码如下所示:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ComboBoxTest
{
// Form uses a ComboBox to select different shapes to draw
public partial class ComboBoxTestForm : Form
{
// constructor
public ComboBoxTestForm()
{
InitializeComponent();
} // end constructor
Pen myPen;
SolidBrush mySolidBrush;
private void imageComboBox_SelectedIndexChanged(
object sender, EventArgs e )
{
// create graphics object, Pen and SolidBrush
Graphics myGraphics = base.CreateGraphics();
// create Pen using color DarkRed
// create SolidBrush using color DarkRed
// clear drawing area setting it to color white
myGraphics.Clear( Color.White );
// find index, draw proper shape
switch ( imageComboBox.SelectedIndex )
{
case 0: // case Circle is selected
myGraphics.DrawEllipse( myPen, 50, 50, 150, 150 );
break;
case 1: // case Rectangle is selected
myGraphics.DrawRectangle( myPen, 50, 50, 150, 150 );
break;
case 2: // case Ellipse is selected
myGraphics.DrawEllipse( myPen, 50, 85, 150, 115 );
break;
case 3: // case Pie is selected
myGraphics.DrawPie(myPen, 50, 50, 150, 150, 0, 45 );
break;
case 4:
Point point1 = new Point(150, 50);
Point point2 = new Point(100, 150);
Point point3 = new Point(200, 150);
Point[] curvePoints =
{
point1,
point2,
point3,
};
myGraphics.DrawPolygon(myPen, curvePoints);
break;
case 5: // case Filled Circle is selected
myGraphics.FillEllipse( mySolidBrush, 50, 50, 150, 150 );
break;
case 6: // case Filled Rectangle is selected
myGraphics.FillRectangle( mySolidBrush, 50, 50, 150,
150 );
break;
case 7: // case Filled Ellipse is selected
myGraphics.FillEllipse( mySolidBrush, 50, 85, 150, 115 );
break;
case 8: // case Filled Pie is selected
myGraphics.FillPie( mySolidBrush, 50, 50, 150, 150, 0,
45 );
break;
case 9:
Point point4 = new Point(150, 50);
Point point5 = new Point(100, 150);
Point point6 = new Point(200, 150);
Point[] curvePoints2 =
{
point4,
point5,
point6,
};
myGraphics.FillPolygon(mySolidBrush, curvePoints2);
break;
} // end switch
myGraphics.Dispose(); // release the Graphics object
}
private void ComboBoxTestForm_Load(object sender, EventArgs e)
{
}
private void colorComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
switch (colorComboBox.SelectedIndex)
{
case 0:
myPen = new Pen(Color.Black);
mySolidBrush = new SolidBrush(Color.Black);
break;
}
}
// end method imageComboBox_SelectedIndexChanged
} // end class ComboBoxTestForm
}
我试图做的是在 void 之外调用 myPen,因此可以在控制颜色的第二个 void 中调用它。 Mysolidbrush 代表形状的填充。在第二个空白中,我尝试将 myPen 称为 black ,但我没有看到任何变化。我想知道我应该采取哪些步骤才能显示我想要的颜色。
【问题讨论】:
-
将所有绘制逻辑放入
Paint事件中,然后在SelectedIndexChanged事件中,调用this.Invalidate(); -
同样在当前代码中,虽然您已将
myPen和mySolidBrush定义为类成员,但您从未初始化它们。在colorComboBox_SelectedIndexChanged中,您分配的是局部变量,而不是类成员。 -
对不起,我对 GUI 很陌生,你能告诉我这是怎么做的吗?
-
我分享了一些伪代码,供您按照您的要求描述评论。希望对您有所帮助 :) 不要忘记为事件分配处理程序。