[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