WinForm畫網格並填充顏色


因為研究CodeCombat上的最后一題,自己嘗試分解題目,然后想到需要畫網格,還有最優化的方法

源代碼如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DrawGrid
{
    public partial class Form1 : Form
    {
        int multiple = 20;
        int width = 20;
        int height = 16;
        int w = 4;
        int h = 4;
        Pen bluePen = new Pen(Color.Black);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Console.WriteLine("Form長:{0},寬:{1}", this.Width, this.Height);
            this.Multiple();
            DrawGrid(width, height, w, h, e);
           
            List<Rectangle> l = new List<Rectangle>();
            Rectangle r;
            r = new Rectangle(0, w, 2 * w, h); l.Add(r);
            r = new Rectangle(3 * w, 0, 2 * w, h); l.Add(r);
            r = new Rectangle(2 * w, 3 * w, 2 * w, h); l.Add(r);
            foreach (Rectangle r1 in l)
            {
                e.Graphics.FillRectangle(new SolidBrush(Color.Black), r1);
            }
        }

        /// <summary>
        /// 將比例放大
        /// </summary>
        private void Multiple()
        {
            width = width * multiple;
            height = height * multiple;
            w = w * multiple;
            h = h * multiple;
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            Console.WriteLine("X={0},Y={1}", e.X, e.Y);
        }

        /// <summary>
        /// 畫網格
        /// </summary>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        private void DrawGrid(int width, int height, int w, int h, PaintEventArgs e)
        {
            Point p1 = new Point();
            Point p2 = new Point();

            p1.X = 0; p2.X = width;
            for (int y = 0; y <= height; y = y + h)
            {
                p1.Y = y; p2.Y = y;
                DrawLine(p1, p2, e);
            }
            p1.Y = 0; p2.Y = height;
            for (int x = 0; x <= width; x = x + w)
            {
                p1.X = x; p2.X = x;
                DrawLine(p1, p2, e);
            }
        }

        /// <summary>
        /// 畫直線
        /// </summary>
        /// <param name="p1"></param>
        /// <param name="p2"></param>
        private void DrawLine(Point p1, Point p2, PaintEventArgs e)
        {
            e.Graphics.DrawLine(bluePen, p1, p2);
        }
    }
}

 

自己的測試圖片如上圖,是一個5*4的網格;

有三個地方已經被填充了。

剩下空白的地方,需可以用矩形填充。

考慮使用最少的矩形填充,應該就是4個矩形了。一目了然。

不過,如果考慮用程序實現的話,就復雜了。以后再嘗試


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM