本系列第九篇,實作「馬賽克效果」:將圖像分割為網格塊,隨機打亂塊順序並逐步還原,呈現動態馬賽克動畫。
dw × dh。MyPoint[2500]。
private void btnMosaic_Click(object sender, EventArgs e)
{
try
{
int dw = MyBitmap.Width / 50;
int dh = MyBitmap.Height / 50;
using (var g = pictureBox1.CreateGraphics())
{
g.Clear(Color.Gray);
var points = new Point[2500];
for (int x = 0; x < 50; x++)
for (int y = 0; y < 50; y++)
points[x * 50 + y] = new Point(x * dw, y * dh);
using (var bmp = new Bitmap(MyBitmap.Width, MyBitmap.Height))
{
// 動畫階段:隨機塊逐步出現
for (int i = 0; i < 10000; i++)
{
int idx = new Random().Next(2500);
CopyBlock(bmp, MyBitmap, points[idx], dw, dh);
pictureBox1.Image = bmp;
pictureBox1.Refresh();
}
// 完成階段:填滿所有塊
for (int i = 0; i < 2500; i++)
CopyBlock(bmp, MyBitmap, points[i], dw, dh);
pictureBox1.Image = bmp;
}
}
}
catch (Exception ex) { MessageBox.Show(ex.Message, "提示"); }
}
void CopyBlock(Bitmap dest, Bitmap src, Point p, int dw, int dh)
{
for (int x = 0; x < dw; x++)
for (int y = 0; y < dh; y++)
dest.SetPixel(p.X + x, p.Y + y, src.GetPixel(p.X + x, p.Y + y));
}

Random 實例。BitmapData 批次複製像素區塊,避免 GetPixel/SetPixel 巨大開銷。Bitmap 操作,最後一次性指派給 PictureBox.Image,減少閃爍。馬賽克動畫展示了塊級像素操作與動態重繪技巧。優化後可流暢運行於高解析度圖像,是拼圖遊戲、轉場特效的基礎實作。