我需要繪製隨機顏色和隨機位置的隨機形狀。 現在我想通了如何使用油漆事件,但它似乎只在我的繪畫事件C#createGraphics,筆只在面板繪畫事件中初始化
private void ShapesPanel_Paint(object sender, PaintEventArgs e)
{
_graphics = ShapesPanel.CreateGraphics();
_pen = new Pen(Color.Black, 1);
}
這個工程中初始化,然後筆工作,但我想隨機顏色和各種形狀都有它自己生成的隨機顏色。
我有這樣的foreach它的工作原理:
foreach (var shape in _shapes)
{
shape.DrawAble(_graphics);
}
現在我想有圖紙不得不形狀顏色:
foreach (var shape in _shapes)
{
_pen = new Pen(shape.Color, 3);
shape.DrawAble(_graphics);
}
,這將不提供任何圖紙都沒有。 有人熟悉? 感謝
窗體類
public partial class ShapesForm : Form
{
private Shape _shape;
private Graphics _graphics;
private Pen _pen;
private Random _random;
private int _red, _blue, _green;
private Color _color;
private int _x, _y;
private Point _point;
private int _randomShape;
private double _size;
private double _radius;
private List<Shape> _shapes;
public ShapesForm()
{
InitializeComponent();
_shapes = new List<Shape>();
_random = new Random();
}
private void ShapesPanel_Paint(object sender, PaintEventArgs e)
{
_graphics = ShapesPanel.CreateGraphics();
_pen = new Pen(Color.Black, 1);
}
private void AddShapeButton_Click(object sender, EventArgs e)
{
_red = _random.Next(0, 255);
_green = _random.Next(0, 255);
_blue = _random.Next(0, 255);
_color = Color.FromArgb(1, _red, _green, _blue);
_x = _random.Next(0, 100);
_y = _random.Next(0, 100);
_point = new Point(_x, _y);
_radius = _random.Next(0, 20);
_size = _random.Next(0, 20);
_randomShape = _random.Next(0, 2);
switch(_randomShape)
{
case 0:
_shape = new Circle(_point, _color, _radius);
_shapes.Add(_shape);
UpdateShapeListBox();
DrawShapes();
break;
case 1:
_shape = new Square(_point, _color, _size);
_shapes.Add(_shape);
UpdateShapeListBox();
DrawShapes();
break;
}
}
public void UpdateShapeListBox()
{
ShapesListBox.Items.Clear();
foreach (var shape in _shapes)
{
ShapesListBox.Items.Add(shape.ToString());
}
}
public void DrawShapes()
{
ShapesPanel.Refresh();
foreach (var shape in _shapes)
{
_pen = new Pen(shape.Color, 3);
shape.DrawAble(_graphics);
}
}
}
不要這樣做。你不應該在外面畫一個'Paint'處理器。 – SLaks
oke ,,所以如何解決?:P仍然newby –
並且不要使用'CreateGraphics()'。使用'e.Graphics',並且只在Paint處理程序(或它調用的方法)內部。 – Blorgbeard