# Qt中国象棋二——棋盘与棋子的绘制

    //窗口以棋盘图片为大小

QPixmap pixChessBoard(":/image/Resources/image/chessBoard.png");

setFixedSize(pixChessBoard.size());

QPalette palette(this->palette());

palette.setBrush( QPalette::Window,QBrush(pixChessBoard));

this->setPalette(palette);

#define RECT_WIDTH    55

#define RECT_HEIGHT    56

#define START_X  (35 - RECT_WIDTH/2)

#define START_Y  (45 - RECT_HEIGHT/2)

RECT_WIDTH

1
2

RECT_HEIGHT

2
3

35,45

是棋盘左上角像素坐标，即与
1 对应

START_X

START_Y

4 的像素坐标

1.  棋子属性类
(Item) 的定义

Item::Item(ITEM_TYPE t,ITEM_COLOR c,QPoint pt)

{

m_type = t;

m_color = c;

m_pt = pt;

m_bShow = true;

}

2.  初始化黑色棋子的逻辑属性

void MainWindow::initItems()

{

m_items.clear();

//初始化所有黑方棋子

Item item1(ITEM_JU,COLOR_BLACK,QPoint(0,0));

Item item2(ITEM_MA,COLOR_BLACK,QPoint(1,0));

Item item3(ITEM_XIANG,COLOR_BLACK,QPoint(2,0));

Item item4(ITEM_SHI,COLOR_BLACK,QPoint(3,0));

Item item5(ITEM_SHUAI,COLOR_BLACK,QPoint(4,0));

Item item6(ITEM_SHI,COLOR_BLACK,QPoint(5,0));

Item item7(ITEM_XIANG,COLOR_BLACK,QPoint(6,0));

Item item8(ITEM_MA,COLOR_BLACK,QPoint(7,0));

Item item9(ITEM_JU,COLOR_BLACK,QPoint(8,0));

Item item10(ITEM_PAO,COLOR_BLACK,QPoint(1,2));

Item item11(ITEM_PAO,COLOR_BLACK,QPoint(7,2));

Item item12(ITEM_BING,COLOR_BLACK,QPoint(0,3));

Item item13(ITEM_BING,COLOR_BLACK,QPoint(2,3));

Item item14(ITEM_BING,COLOR_BLACK,QPoint(4,3));

Item item15(ITEM_BING,COLOR_BLACK,QPoint(6,3));

Item item16(ITEM_BING,COLOR_BLACK,QPoint(8,3));

m_items.push_back(item1);

m_items.push_back(item2);

m_items.push_back(item3);

m_items.push_back(item4);

m_items.push_back(item5);

m_items.push_back(item6);

m_items.push_back(item7);

m_items.push_back(item8);

m_items.push_back(item9);

m_items.push_back(item10);

m_items.push_back(item11);

m_items.push_back(item12);

m_items.push_back(item13);

m_items.push_back(item14);

m_items.push_back(item15);

m_items.push_back(item16);

}

3.  绘制棋子

①从图片中切割棋子

drawPixmap(rcTarget,
m_itemImage
,rcSrc)

void

paintEvent

(
QPaintEvent

*)

void MainWindow::paintEvent(QPaintEvent *)

{

QPainter painter(this);

for (int i = 0; i

{

drawItem(painter,m_items[i]);

}

# if 0   //方便理解棋盘中宏定义的位置

painter.setPen(QPen(Qt::blue,5));

painter.drawPoint(35,45);

painter.drawPoint(90,45);

painter.drawPoint(90,101);

painter.drawPoint(START_X,START_Y);

#endif

//    update();

}

② 绘制棋子
OK，接下来看下drawItem()

painter  是事件中传入的，

i
tem

是类中定义所有棋子属性的容器，

QVector
<
Item
>

m_items
;

void MainWindow::drawItem(QPainter &painter, Item item)

{

if (!item.m_bShow)

{

return;

}

//根据顺序切割棋子图片像素位置

QRect rcSrc(m_nItemWidth*item.m_color,m_nItemHeight*item.m_type,

m_nItemWidth,m_nItemHeight);

//将对应棋子的逻辑位置映射为棋盘上的像素位置

QRect rcTarget( START_X + item.m_pt.x()*RECT_WIDTH,

START_Y + item.m_pt.y()*RECT_HEIGHT,

RECT_WIDTH,RECT_HEIGHT);

//在棋盘上绘制m_itemImage中对应的像素棋子

painter.drawPixmap(rcTarget,m_itemImage,rcSrc);

}