Can you make for me Graph in GDI

Samir ⚽⚽⚽ 0 Reputation points
2025-04-28T19:41:24.0333333+00:00

I need help with making some basic graphs in GDI for winforms

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,431 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Max 0 Reputation points
    2025-04-28T19:42:54.3766667+00:00

    public partial class GraphForm : Form

    {

    public GraphForm()

    {

    InitializeComponent();

    }

    private void pictureBox_Graph_Paint(object sender, PaintEventArgs e)

    { Graphics g = e.Graphics;

    // Odsazení grafu od stran int padding = 30;

    // Posun startY výš kvůli zobrazení celého otočeného textu

    int startX = padding; int startY = pictureBox_Graph.Height - padding - 100;

    int endX = pictureBox_Graph.Width - padding;

    // Vykreslím osu X

    g.DrawLine(Pens.Black, startX, startY + padding / 2, startX, padding);

    // Vykreslím osu Y

    g.DrawLine(Pens.Black, startX - padding / 2, startY, endX, startY);

    // Načtu data z DB AppDbContext dbContext = new AppDbContext();

    List<Company> companies = dbContext.Companies .Include(c => c.JobOffers) .OrderByDescending(c => c.JobOffers.Count) .ToList();

    if (companies.Count == 0) return;

    int maxJobsCount = companies.Max(c => c.JobOffers.Count);

    int yAxisHeight = startY - padding;

    int heightPerUnitCol = yAxisHeight / Math.Max(1, maxJobsCount);

    // ochrana proti dělení nulou

    int spaceBetweenColumns = 50;

    int columnWidth = 20;

    Color[] columnColors = new Color[] { Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Purple, Color.Cyan };

    int colorIndex = 0;

    foreach (Company company in companies)

    {

    startX += spaceBetweenColumns;

    int count = company.JobOffers.Count;

    int columnHeight = heightPerUnitCol * count;

    Color columnColor = columnColors[colorIndex % columnColors.Length];

    g.FillRectangle(new SolidBrush(columnColor), startX, startY - columnHeight, columnWidth, columnHeight);

    // Vykreslení názvu firmy pod sloupec (otočený text)

    string companyName = company.Name;

    Font font = new Font("Arial", 10); SizeF textSize = g.MeasureString(companyName, font);

    float textX = startX + (columnWidth / 2) - (textSize.Height / 2);

    // zarovnat na střed pro rotovaný text

    float textY = startY + 35;

    // větší mezera pod osou X

    GraphicsState state = g.Save();

    g.TranslateTransform(textX, textY);

    g.RotateTransform(90);

    g.DrawString(companyName, font, Brushes.Black, 0, -15);

    g.Restore(state); startX += columnWidth; colorIndex++; } } } }

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.