載入位圖,掃描每一掃描線,找出非透明色像素的連續區間,將其轉換為矩形區域 (RECT) 陣列,最後呼叫 ExtCreateRegion 建立複合區域並套用至視窗。
Graphics::TBitmap* Sprite = new Graphics::TBitmap();
bool bKey = true;
int iCount = 0;
TColor ColorKey = clWhite;
Sprite->LoadFromFile("D:\\bcbbak\\resource\\traffic.bmp");
Width = Sprite->Width; Height = Sprite->Height;
// 第一遍掃描:計算矩形數量
for (int i = 0; i < Sprite->Height; i++) {
bKey = true;
for (int j = 0; j < Sprite->Width; j++) {
if (Sprite->Canvas->Pixels[j][i] == ColorKey) bKey = true;
else { if (bKey) iCount++; bKey = false; }
}
}
// 配置 RGNDATA 結構記憶體
byte* pData = new Byte[sizeof(RGNDATAHEADER) + sizeof(RECT) * iCount];
RGNDATA* pRgnData = (RGNDATA*)pData;
RECT* pRect = (RECT*)(pData + sizeof(RGNDATAHEADER));
pRgnData->rdh.dwSize = sizeof(RGNDATAHEADER);
pRgnData->rdh.iType = RDH_RECTANGLES;
pRgnData->rdh.nCount = iCount;
pRgnData->rdh.nRgnSize = sizeof(RECT) * iCount;
pRgnData->rdh.rcBound.left = 0;
pRgnData->rdh.rcBound.top = 0;
pRgnData->rdh.rcBound.right = Sprite->Width;
pRgnData->rdh.rcBound.bottom = Sprite->Height;
// 第二遍掃描:填入矩形座標(注意 Y 軸翻轉)
for (int i = Sprite->Height - 1; i >= 0; i--) {
bKey = TRUE; iLeft = -1;
for (int j = 0; j < Sprite->Width; j++) {
if (Sprite->Canvas->Pixels[j][i] == ColorKey) {
if (!bKey) {
pRect[iIndex].left = iLeft;
pRect[iIndex].right = j;
pRect[iIndex].top = Sprite->Width - i - 1;
pRect[iIndex].bottom = Sprite->Height - i;
bKey = TRUE; iIndex++; iLeft = -1;
}
} else if (bKey) { iLeft = j; bKey = false; }
}
if (iLeft >= 0) {
pRect[iIndex].left = iLeft;
pRect[iIndex].right = Sprite->Width;
pRect[iIndex].top = i;
pRect[iIndex].bottom = i;
iIndex++;
}
}
// 建立區域並套用
bool br = ExtCreateRegion(NULL, sizeof(RGNDATAHEADER) + sizeof(RECT) * iCount, pRgnData);
if (!br) { ShowMessage("Create Form Failed."); Close(); }
delete[] pData;