如何使用C#从外部文件获取动态多边形坐标并在PictureBox中绘制
Got it, let's tweak your code to load dynamic polygon points from an external file instead of using hardcoded values. First, we'll fix a couple of small issues in your original code, then add the file-reading logic step by step.
First: Clean Up the Original Paint Event Code
Your current code has a few inefficiencies and potential bugs:
- You don't need both
CreateGraphics()andGraphics.FromImage()—we'll stick withFromImagesince we're drawing directly to the PictureBox's image. - Always use
usingstatements for disposable objects (likeGraphicsandPen) to avoid memory leaks, instead of manually callingDispose(). - Calling
pictureBox1.Refresh()inside the Paint event can trigger infinite repaint loops—we'll remove that.
Step 1: Define Your Coordinate File Format
First, create a text file (let's name it polygonPoints.txt) where each line represents a point in x,y format. For example:
100,100 200,100 300,200 200,200 100,400
Place this file in your application's output directory, or use a full file path to specify its location later.
Step 2: Add a Helper Method to Read & Parse Coordinates
Create a method that reads the file, parses each line into a Point object, and returns an array of points:
private Point[] LoadPolygonPointsFromFile(string filePath) { var pointsList = new List<Point>(); // Check if the file exists first to avoid errors if (!File.Exists(filePath)) { MessageBox.Show($"File not found: {filePath}"); return Array.Empty<Point>(); } try { // Read all lines from the file at once string[] lines = File.ReadAllLines(filePath); foreach (string line in lines) { // Split each line by comma to extract x and y values string[] coordinates = line.Split(',', StringSplitOptions.RemoveEmptyEntries); // Validate we have two valid integers before creating a point if (coordinates.Length == 2 && int.TryParse(coordinates[0], out int x) && int.TryParse(coordinates[1], out int y)) { pointsList.Add(new Point(x, y)); } else { MessageBox.Show($"Invalid line format: {line}. Skipping this point."); } } } catch (Exception ex) { MessageBox.Show($"Error reading file: {ex.Message}"); } return pointsList.ToArray(); }
Step 3: Update the Paint Event & Initialize the PictureBox Image
First, add a Form Load event handler to set up a blank image for the PictureBox (so we have something to draw on):
private void Form1_Load(object sender, EventArgs e) { // Create a blank bitmap matching the PictureBox's size pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height); }
Then update the Paint event to use the dynamically loaded points:
private void pictureBox1_Paint(object sender, PaintEventArgs e) { // Use using to automatically dispose the Graphics object when done using (Graphics g = Graphics.FromImage(pictureBox1.Image)) { // Clear the image to avoid overlapping draws from previous repaints g.Clear(pictureBox1.BackColor); // Load points from your file (use a full path if the file isn't in the app directory) string filePath = "polygonPoints.txt"; Point[] polygonPoints = LoadPolygonPointsFromFile(filePath); // A polygon needs at least 3 points to draw—only proceed if we have enough if (polygonPoints.Length >= 3) { using (Pen p = new Pen(Color.Black, 5)) { g.DrawPolygon(p, polygonPoints); } } else { MessageBox.Show("Not enough valid points to draw a polygon."); } } // Tell the PictureBox to redraw with the updated image pictureBox1.Invalidate(); }
Quick Notes:
- File Path: If your text file isn't in the same folder as your executable, use an absolute path like
@"C:\MyProjects\PolygonApp\polygonPoints.txt". - Error Handling: The helper method includes basic checks for missing files and invalid lines—you can expand this logic based on your needs.
- Minimum Points: We check for at least 3 points because you can't draw a polygon with fewer than that.
内容的提问来源于stack exchange,提问作者Shucks Afgee

