如何切割9件图像并控制宽度和高度?

时间:2014-12-21 18:52:51

标签: c#

嗨,大家好我在这段代码中有问题我希望显示我的9张照片,并将其显示在9个图片框中,以制作益智游戏,希望任何人都能提供帮助。 在此先感谢

var knight = new Image[9];
var H = Image.FromFile("1425435_630471227004342_2061223205_o.jpg");
for (int i = 0; i < 3; i++)
 {
    for (int j = 0; j < 3; j++)
    {

      var index = i * 3 + j;
      knight[index] = new Bitmap(200,200);
      var m = Graphics.FromImage(knight[index]);
      Rectangle r = new Rectangle( i * (knight[index].Width / 3),
                                   j*(knight[index].Height / 3), 
                                   knight[index].Width / 3, 
                                   knight[index].Height / 3);
      m.DrawImage(H, r, r, GraphicsUnit.Pixel);

      m.Dispose();
    }
 }
 pictureBox1.Image = knight[0];
 pictureBox2.Image = knight[1];
 pictureBox3.Image = knight[2];
 pictureBox4.Image = knight[3];
 pictureBox5.Image = knight[4];
 pictureBox6.Image = knight[5];
 pictureBox7.Image = knight[6];
 pictureBox8.Image = knight[7];
 pictureBox9.Image = knight[8];

2 个答案:

答案 0 :(得分:0)

更改此

  Rectangle r = new Rectangle( i * (knight[index].Width / 3),
                               j*(knight[index].Height / 3), 
                               knight[index].Width / 3, 
                               knight[index].Height / 3);
  m.DrawImage(H, r, r, GraphicsUnit.Pixel);

到此:

  out of the loop:
  // old size of the parts:
  int ow = H.Width / 3;
  int oh = H.Height / 3;

  // new size of the parts:
  int nw = knight[0].Width;
  int nh = knight[0].Height;

  // inner loop:
  Rectangle rDest   = new Rectangle(0, 0, nw, nh);
  Rectangle rSource = new Rectangle(i * ow, j * oh, ow, oh);

  m.DrawImage(H, rDest, rSource , GraphicsUnit.Pixel);

注意:如果原始图像和9 PB的比例不同,则会出现失真:

enter image description here

答案 1 :(得分:0)

您没有使用单独的源矩形(如TaW所述)。此外,您还没有完全占据picturebox

试试这段代码:

knight[index] = new Bitmap(640, 360); //enter the size of the original image

Rectangle src = new Rectangle(i * (knight[index].Width / 3), j * (knight[index].Height / 3), knight[index].Width / 3, knight[index].Height / 3);
Rectangle des = new Rectangle(0, 0, knight[index].Width, knight[index].Height);
m.DrawImage(H, des, src, GraphicsUnit.Pixel);