Colin Roe
Colin Roe

Reputation: 804

How to place a cropped image on a canvas? wpf c#

In my code, I select an image and is cropped into 9 pieces. Now I want to randomly position each piece in my canvas. How would I go about doing that?

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);
    }

Upvotes: 0

Views: 764

Answers (2)

Jigsore
Jigsore

Reputation: 21

Try the following:

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);
        }
}

Upvotes: 2

Nicholas Pappas
Nicholas Pappas

Reputation: 10624

Is there a requirement that the images must be placed directly onto a canvas element? If you know the number of sub-images you will end up with, you can more easily create a series of Image elements in your XAML and then set their Source attribute to the image sub-sections.

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

You'd have individual elements for each sub-image and would be able to move them around the canvas as you wish.

Upvotes: 1

Related Questions