C#繪製中國象棋棋盤
阿新 • • 發佈:2021-01-20
在C#繪製中國象棋棋盤是C#程式設計中GDI+的一個重要組成部分。這也是非常考驗程式設計技巧的操作。在繪製之前首先要對棋盤有一個完整的認識。下面是完成後的輸出圖案。
1.在製作過程中用到了背景圖片如下:
2.棋盤的橫豎交叉線的座標如下圖(棋盤橫向、豎向都以50象素間距繪製)
3.更細的座標分佈如下圖
完整的程式碼如下圖
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Chinese_chessboard { public partial class FrmMain : Form { public FrmMain() { InitializeComponent(); } private void FrmMain_Paint(object sender,PaintEventArgs e) { if (!File.Exists(Application.StartupPath + @"\" + "bg.jpg")) { MessageBox.Show("請把素材中的bg.jpg圖片檔案放到可執行程式相同資料夾中,並重新啟動程式!","提示"); Application.Exit(); } Console.WriteLine("C#程式設計交流群:485532597"); Graphics g = e.Graphics; // 獲取一個Graphics物件 g.Clear(Color.Coral); //用珊瑚色清除窗體 Font font1 = new Font("黑體",25,FontStyle.Regular); int s = (int)(font1.Size / 0.6); int s2 = (int)font1.Height; Image img = Image.FromFile("bg.jpg"); g.DrawImage(Image.FromFile(Application.StartupPath + @"\" + "bg.jpg"),10,430,480); //繪製背景圖 g.DrawRectangle(new Pen(Color.Black,3),new Rectangle(new Point(20,20),new Size(410,460))); //繪製框圖 Pen pen = new Pen(Color.Black,1); //繪製水平線 for (int i = 0; i < 10; i++) { g.DrawLine(pen,new Point(25,25 + (i * 50)),new Point(425,25 + (i * 50))); } //繪製垂直線 for (int i = 0; i < 9; i++) { g.DrawLine(pen,new Point(25 + (i * 50),25),225)); g.DrawLine(pen,275),475)); } //return; //繪製將士位置斜線 g.DrawLine(pen,new Point(175,new Point(275,125)); g.DrawLine(pen,375),475)); g.DrawLine(pen,475),375)); //兵位(炮位)線,只畫一個 g.DrawLine(pen,new Point(30,160),170)); g.DrawLine(pen,170),new Point(40,180),190)); g.DrawLine(pen,180)); g.DrawString("楚 河",new Font("黑體",Brushes.Black,new Point(50,235)); g.TranslateTransform(300,235); //平移座標軸 g.RotateTransform(180); //進行180度旋轉 g.DrawString("漢 界",new Point(-100,-35)); g.ResetTransform(); //座標軸復位 this.DrawAngle(g,pen,new Point(125,175),"all"); this.DrawAngle(g,"left"); this.DrawAngle(g,new Point(225,new Point(325,new Point(75,125),new Point(375,"all"); this.DrawAngle(g,325),"right"); this.DrawAngle(g,"all"); g.Dispose(); //釋放物件 } private void DrawAngle(Graphics g,Pen pen,Point point,string str) { Point p1 = new Point(point.X + 5,point.Y + 5); Point p2= new Point(point.X - 5,point.Y + 5); Point p3= new Point(point.X -5,point.Y - 5); Point p4 = new Point(point.X +5,point.Y -5); if(str=="right"||str=="all") { //p1 p4 g.DrawLine(pen,p1,new Point(p1.X + 10,p1.Y)); g.DrawLine(pen,new Point(p1.X,p1.Y+10)); g.DrawLine(pen,p4,new Point(p4.X + 10,p4.Y)); g.DrawLine(pen,new Point(p4.X,p4.Y-10)); } if(str=="left" || str == "all") { //p2 p3 g.DrawLine(pen,p2,new Point(p2.X - 10,p2.Y)); g.DrawLine(pen,new Point(p2.X,p2.Y+10)); g.DrawLine(pen,p3,new Point(p3.X - 10,p3.Y)); g.DrawLine(pen,new Point(p3.X,p3.Y - 10)); } } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。