[C#] 分割圖片

練習製作滑塊拼圖小遊戲,必須用到圖片切割,所以去找了一下其實還蠻簡單的,System.Drawing.Bitmap 就有方法了,此知識來自 StackOverFlow : How to crop an image using C#?

  using System.IO;
  try
  {
    Image img = Image.FromFile(@"C:\.....\sample.jpg");
    Bitmap bmp = (Bitmap)img;
  }
  catch(FileNotFoundException ex)
  {

  }
  Rectangle rect = new Rectangle(100, 180, 300, 200);
  Image result = bmp.Clone(rect, img.PixelFormat);

上面的程式碼就會將 sample.jpg 圖片上 (100, 180) 的位置開始切下寬300、高200的長方形賦予給 result,下為示意圖片:

就會得到黃色矩形的圖片,如下

要如影片切割成多塊來移動,我是用 PictureBox[] ,要注意的是第幾個 row 其實在坐標上有關的是 y 坐標,而第幾個 column 對應的是 x 坐標,另外因為 PictureBox 是另外 new 出來不是手動滑鼠拉的,必須有 Form.Controls.Add() 來讓他出現在視窗上。

  using System.IO;
  PictureBox[] picBlock = new PictureBox[16];
  int blockWidth, blockHeight;

  try
  {
    Image img = Image.FromFile(@"C:\.....\sample.jpg");
    Bitmap bmp = (Bitmap)img;
    blockWidth = img.Width / 4;
    blockHeight = img.Height / 4;
  }
  catch(FileNotFoundException ex)
  {

  }
  for(int i=0; i<16; i++)         // i % 4 會得陣列中 column 位置,可換算 x 坐標
  {                               // i / 4 會得陣列中 row 位置,可換算 y 坐標
    int x = (i % 4) * blockWidth;       // 切割小塊圖片的位置
    int y = (i / 4) * blockHeight;      // 同時也是從sample.jpg什麼位置開始切割
    picBlock[i] = new PictureBox();
    picBlock[i].SizeMode = PictureBoxSizeMode.AutoSize;   // 大小設定成自動縮放
    picBlock[i].Location = new Point(x, y);
    Rectangle rect = new Rectangle(x, y, blockWidth, blockHeight);
    picBlock[i].Image = bmp.Clone(rect, img.PixelFormat);
    this.Controls.Add(picBlock[i]);     // 此處的 this 指 Form
  }

留言