CourseWorkKnapsack/classes/KnapsackVisualizer.cs
2024-05-20 02:52:44 +04:00

62 lines
2.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using ProjectKnapsack.forms;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static ProjectKnapsack.classes.KnapsackParameters;
namespace ProjectKnapsack.classes;
public class KnapsackVisualizer
{
public void Visualize(List<Item> items, int capacity, MainForm form)
{
PictureBox? pictureBox = form.Controls["pictureBox1"] as PictureBox;// получаем ссылку на PictureBox на форме
Bitmap bitmap = new Bitmap(pictureBox.Width, pictureBox.Height);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.Clear(Color.White);
// Отрисовка рюкзака
int knapsackWidth = 100;
int knapsackHeight = 200;
int knapsackX = 50;
int knapsackY = pictureBox.Height / 2 - knapsackHeight / 2;
graphics.FillRectangle(Brushes.LightGray, knapsackX, knapsackY, knapsackWidth, knapsackHeight);
graphics.DrawRectangle(Pens.Black, knapsackX, knapsackY, knapsackWidth, knapsackHeight);
// Добавление текста "Капацитет" рядом с рюкзаком
string capacityText = "Capacity: " + capacity;
graphics.DrawString(capacityText, SystemFonts.DefaultFont, Brushes.Black, knapsackX + knapsackWidth + 10, knapsackY);
// Отрисовка выбранных предметов
int startX = 200;
int startY = 50;
int spacingX = 150;
foreach (var item in items)
{
int itemWidth = item.Weight;
int itemHeight = item.Value;
int itemX = startX + items.IndexOf(item) * spacingX;
int itemY = startY;
// Отрисовка прямоугольника, представляющего предмет
graphics.FillRectangle(Brushes.LightBlue, itemX, itemY, itemWidth, itemHeight);
graphics.DrawRectangle(Pens.Black, itemX, itemY, itemWidth, itemHeight);
// Добавление текста с именем предмета
string itemName = item.Name;
graphics.DrawString(itemName, SystemFonts.DefaultFont, Brushes.Black, itemX, itemY + itemHeight + 5);
}
}
pictureBox.Image = bitmap; // Отображение изображения на PictureBox
}
}