首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 超酷圖像特效(九):馬賽克效果實作

     編輯:關於C語言

前言

本系列第九篇,實作「馬賽克效果」:將圖像分割為網格塊,隨機打亂塊順序並逐步還原,呈現動態馬賽克動畫。

效果原理

  1. 將圖像分為 50×50 網格,每塊大小 dw × dh。
  2. 建立網格中心點陣列 MyPoint[2500]。
  3. 執行 10000 次迴圈:每次隨機選一塊,複製該塊像素到目標位圖,重繪顯示 (動畫幀)。
  4. 最後完整複製所有塊,還原完整圖像。

完整程式碼


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 建構:迴圈外建立單一 Random 實例。
  • LockBits:以 BitmapData 批次複製像素區塊,避免 GetPixel/SetPixel 巨大開銷。
  • 雙緩衝:直接對 Bitmap 操作,最後一次性指派給 PictureBox.Image,減少閃爍。

結語

馬賽克動畫展示了塊級像素操作與動態重繪技巧。優化後可流暢運行於高解析度圖像,是拼圖遊戲、轉場特效的基礎實作。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved