相反,您可以簡單地將棋子繪製到Paint
事件中的控制表面上。我實現了一個初步的解決方案,這裏是Paint
事件如此:
List<ChessPiece> pieces = new List<ChessPiece>();
int mpIndex = -1; // index of the moving piece
Rectangle mmr; // rectangle where moving piece is drawn
// board display variables
int pieceSize = 60;
int tileSize = 80;
int borderWidth = 50;
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
foreach(ChessPiece p in pieces)
{
if (!p.onBoard) continue; // skip the piece?
e.Graphics.DrawImage(imageList1.Images[p.pieceIndex],
borderWidth + p.col * tileSize,
borderWidth + p.row * tileSize);
}
// if we have a moving piece..
if (mpIndex >= 0 && !pieces[mpIndex].onBoard)
e.Graphics.DrawImage(imageList1.Images[pieces[mpIndex].pieceIndex],
mmr.Location);
}
正如你可以看到它確實不是很長。它使用了一些明顯的變量和一些不太明顯的變量。必須事先準備pieces
列表和ImageList
。矩形mmr
設置在MouseMove
:
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
mmr = new Rectangle(e.X - pieceSize/2,
e.Y - pieceSize/2, pieceSize, pieceSize);
pictureBox1.Invalidate(); // trigger the painting
}
}
我不會發布MouseUp
和-Down
事件,因爲它們含有大部分代碼,實際上並不屬於移動的透明圖像,但在管理片的名單..
最主要的想法是從一個棋子列表中繪製所有圖像,除非棋子不在棋盤上。移動件是分開繪製的,它的座標不是來自板的位置,而是來自鼠標的位置。
如果在MouseUp
事件中我們發現該移動是非法的,我們可以簡單地將其設置爲onBoard
而不更改位置並將其繪製在舊位置。
在MouseDown
我們確定點擊的那一塊,設置它的onBoard=false
並設置移動索引mpIndex
。
作品的類別不長或複雜;
public class ChessPiece
{
public bool onBoard { get; set; } // is the piece standing on the board?
public int row { get; set; } // row
public int col { get; set; } // column
public char piecetype { get; set; } // a little simplistic..not used..
public char color { get; set;} // .. could be an enumeration!
public int pieceIndex { get; set; } // points into imageList with 12 images
public ChessPiece(char color, char type, int r, int c, int ind)
{ onBoard = true; piecetype = type; this.color = color;
row = r; col = c; pieceIndex = ind; }
}
總而言之的完整代碼是大約180行,未註釋的,但包括60行和單獨沒有任何國際象棋邏輯建立塊..
這裏是前3行的代碼以創建件:
void makePieces()
{
ChessPiece
p = new ChessPiece('W', 'R', 7, 0, 8); pieces.Add(p);
p = new ChessPiece('W', 'N', 7, 1, 10); pieces.Add(p);
p = new ChessPiece('W', 'B', 7, 2, 9); pieces.Add(p);
..
所以,移動的透明Png
圖形相對於其它Png
圖形和一個板圖像是相當簡單.. 這裏是一個屏幕截圖,顯示了黑色的主教在白騎士:
![enter image description here](https://i.stack.imgur.com/AOiAP.png)
這不是很清楚你在問什麼。你想知道如何使你的PNG透明,或如何讓你的圖像拖動? – thomasb 2015-02-23 16:06:30
Winforms透明度是一種黑客攻擊,它只需要它背後的任何顏色......如果你發佈了一個鏈接到圖像本身,有人將能夠編輯圖像到你的問題,這可能會讓你的問題更清晰 – Sayse 2015-02-23 16:12:58
這將不行。對於國際象棋棋盤,請考慮在面板背景圖像(或圖像)中設置整個棋盤,並將棋子繪製到表面上。然後,您可以在繪製時使用面板內部的__one__ PictureBox,或者更自然地更新移動件在鼠標移動中的位置。爲此,您需要將移動塊作爲最後一塊放在您的列表中,因此它始終位於頂部。 – TaW 2015-02-23 19:00:09