Untitled
unknown
csharp
a month ago
3.9 kB
3
Indexable
Never
private List<CakeLayer> cakeLayers = new List<CakeLayer>(); public Form1() { InitializeComponent(); this.Paint += new PaintEventHandler(this.Form1_Paint); this.Load += new EventHandler(this.Form1_Load); this.btnAddLayer.Click += new EventHandler(this.BtnAddLayer_Click); this.btnRemoveLayer.Click += new EventHandler(this.BtnRemoveLayer_Click); this.btnChooseColor.Click += new EventHandler(this.BtnChooseColor_Click); this.lstLayers.SelectedIndexChanged += new EventHandler(this.LstLayers_SelectedIndexChanged); this.numLayerHeight.ValueChanged += new EventHandler(this.LayerPropertiesChanged); this.numLayerWidth.ValueChanged += new EventHandler(this.LayerPropertiesChanged); } private void Form1_Load(object sender, EventArgs e) { // Predefine some cake layers cakeLayers.Add(new CakeLayer(50, 200, Color.Pink)); cakeLayers.Add(new CakeLayer(40, 180, Color.LightBlue)); cakeLayers.Add(new CakeLayer(30, 160, Color.LightGreen)); // Populate the list box UpdateLayerList(); cakePanel.Invalidate(); // Force the panel to redraw with the initial layers } private void UpdateLayerList() { lstLayers.Items.Clear(); for (int i = 0; i < cakeLayers.Count; i++) { lstLayers.Items.Add($"Layer {i + 1}"); } } private void BtnAddLayer_Click(object sender, EventArgs e) { CakeLayer newLayer = new CakeLayer((int)numLayerHeight.Value, (int)numLayerWidth.Value, Color.Pink); cakeLayers.Add(newLayer); UpdateLayerList(); lstLayers.SelectedIndex = lstLayers.Items.Count - 1; // Select the new layer cakePanel.Invalidate(); } private void BtnRemoveLayer_Click(object sender, EventArgs e) { if (lstLayers.SelectedIndex >= 0) { cakeLayers.RemoveAt(lstLayers.SelectedIndex); UpdateLayerList(); cakePanel.Invalidate(); } } private void BtnChooseColor_Click(object sender, EventArgs e) { if (lstLayers.SelectedIndex >= 0 && colorDialog.ShowDialog() == DialogResult.OK) { cakeLayers[lstLayers.SelectedIndex].Color = colorDialog.Color; cakePanel.Invalidate(); } } private void LstLayers_SelectedIndexChanged(object sender, EventArgs e) { if (lstLayers.SelectedIndex >= 0) { CakeLayer selectedLayer = cakeLayers[lstLayers.SelectedIndex]; numLayerHeight.Value = selectedLayer.Height; numLayerWidth.Value = selectedLayer.Width; } } private void LayerPropertiesChanged(object sender, EventArgs e) { if (lstLayers.SelectedIndex >= 0) { CakeLayer selectedLayer = cakeLayers[lstLayers.SelectedIndex]; selectedLayer.Height = (int)numLayerHeight.Value; selectedLayer.Width = (int)numLayerWidth.Value; cakePanel.Invalidate(); } } private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; int yPosition = cakePanel.Height; foreach (var layer in cakeLayers) { yPosition -= layer.Height; Rectangle layerRect = new Rectangle((cakePanel.Width - layer.Width) / 2, yPosition, layer.Width, layer.Height); g.FillRectangle(new SolidBrush(layer.Color), layerRect); g.DrawRectangle(Pens.Brown, layerRect); } } } }
Leave a Comment