2012-10-21 83 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); 
     } 
}