簡體   English   中英

(C#) 從文本文件加載以創建圖片框網格

[英](C#) Load from text file to create a grid of picture boxes

我正在嘗試從格式如下的文本文件加載:

a - Total Number of rows in file
b - Total Number of columns in file
x - Row Value for each picture box
y - Column Value for each picture box
z - Picture Value for each picture box

a 和 b 將用於創建圖片框網格。 x 和 y 和 z 用於放置每個圖片框,並設置其圖片 x,y 和 z 部分重復直到網格已滿。

文件示例:

2
2
0
0
0
1
0
1
0
1
2
1
1
3

此示例適用於 2 x 2 網格,因此第一個圖片框位於 0,0 並且圖片值為 0。您 go 如何獲取此信息並創建圖片框網格?

為什么要在文件中列出坐標? 如果您將數字或行和列列為前兩行,那么您可以簡單地列出每個 PB 的值。 您只需要決定值的順序。

例如,如果您首先按行列出:

2
2
0
1
2
3

這意味着我們有一個具有以下值的 2x2 板:

(0, 0) = 0
(1, 0) = 1
(0, 1) = 2
(1, 1) = 3

獲取行數/列數后,您可以使用一組嵌套的 for 循環來讀取每一行的值,了解每一行的去向:

private void button1_Click(object sender, EventArgs e)
{
    int rows, cols, z;

    Point pbOrigin = new Point(10, 10);
    Size pbSize = new Size(50, 50);

    String filePath = @"C:\Users\mikes\Documents\Test\data.txt";           
    try
    {
        using (StreamReader sr = new StreamReader(filePath))
        {
            rows = int.Parse(sr.ReadLine());
            cols = int.Parse(sr.ReadLine());
            Console.WriteLine($"rows: {rows}, cols: {cols}");

            for (int row=0; row<rows; row++)
            {
                for(int col=0; col<cols; col++)
                {
                    z = int.Parse(sr.ReadLine());
                    PictureBox pb = new PictureBox();
                    pb.BorderStyle = BorderStyle.FixedSingle; // just so I can see it
                    pb.Location = new Point(pbOrigin.X + col * pbSize.Width, pbOrigin.Y + row * pbSize.Height);
                    pb.Size = pbSize;
                    // ... do something with "z" ...
                    // pb.Image = z;
                    Console.WriteLine($"({col}, {row}) = {z}");
                    panel1.Controls.Add(pb);
                }
            }
        }

    }
    catch (Exception ex)
    {
        MessageBox.Show("Error Reading File: " + ex.ToString());
        
    }            
}

界面:

在此處輸入圖像描述

控制台 Output:

rows: 2, cols: 2
(0, 0) = 0
(1, 0) = 1
(0, 1) = 2
(1, 1) = 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM