2012-10-21 49 views
0

在我的代码中,我选择了一个图像并裁剪成9个部分。现在我想随机将每件作品放在画布上。我会怎么做呢?如何在画布上放置裁剪图像? wpf c#

public void CutImage(string img) 
    { 
     int count = 0; 

     BitmapImage src = new BitmapImage(); 
     src.BeginInit(); 
     src.UriSource = new Uri(img, UriKind.Relative); 
     src.CacheOption = BitmapCacheOption.OnLoad; 
     src.EndInit(); 

     for (int i = 0; i < 3; i++) 
     { 
      for (int j = 0; j < 3; j++) 
      { 
       objImg[count++] = new CroppedBitmap(src, new Int32Rect(j * 120, i * 120, 120, 120)); 
      } 
     } 
    } 

    public void PositionImage(object[] objImage) 
    { 
     for (int i = 0; i < objImage.Length; i++) 
     { 
      TranslateTransform translateTransform1 = new TranslateTransform(rnd1.Next(1,360), rnd1.Next(1,360)); 
     } 

     //movedRectangle.RenderTransform = translateTransform1; 

     //mainCanvas.Children.Add(movedRectangle); 
    } 

回答

1

是否有要求图像必须直接放置在画布元素上?如果您知道最终的子图像的数量,则可以更轻松地在XAML中创建一系列图像元素,然后将其Source属性设置为图像子部分。

<Canvas> 
    <Image Name="subimg1"> 
    <Image Name="subimg2"> 
    <Image Name="subimg3"> 
    ... 
</Canvas> 

你会有每个子图像的个别元素,并且能够随意移动它们在画布周围。

2

尝试以下操作:

public void PositionImage(BitmapSource[] objImage) 
{ 
    int a, x, y; 
    BitmapSource t; 
    Image img; 

    // Shuffle the array 
    for (a = 0; a < (objImage.Length * 2);) 
    { 
     x = rnd1.Next(objImage.Length); 
     y = rnd1.Next(objImage.Length); 
     if (x != y) 
     { 
      t = objImage[x]; 
      objImage[x] = objImage[y]; 
      objImage[y] = t; 
      a++; 
     } 
    } 
    for (a = y = 0; y < 3; y++) 
     for (x = 0; x < 3; x++) 
     { 
      img = new Image(); 
      img.Source = objImage[a++]; 
      img.Width = img.Height = 120; 
      Canvas.SetLeft(img, x * 120); 
      Canvas.SetTop(img, y * 120); 
      mainCanvas.Children.Add(img); 
     } 
}