PDA

View Full Version : Random Translate Transform



psychman
March 16th, 2009, 04:13 AM
Hello. I am programmatically displaying image thumbnails on a canvas and they all stack up in the upper left corner. I want to have them start in the upper left corner, but then reposition to a random location on the canvas. The problem I am running into is that I can get them to display somewhat randomly, but the group of images all seem to follow a diagonal path from the upper left down toward the lower right of the canvas. They appear to be positioned randomly within that straight diagonal path, but not randomly in relation to the entire canvas. Any help would be great. Here is some code:

Random myRandom1 = new Random();
Random myRandom2 = new Random();
int rand1 = myRandom1.Next(0,400);
int rand2 = myRandom2.Next(0,400);
TranslateTransform positionTransform = new TranslateTransform();
positionTransform.X = rand1;
positionTransform.Y = rand2;
TransformGroup transformGroup = new TransformGroup();
transformGroup.Children.Add(positionTransform);
myImage.RenderTransformOrigin = new Point(0.5, 0.5);
myImage.RenderTransform = transformGroup;

kirupa
March 16th, 2009, 04:42 AM
Hi psychman!
You mentioned that you are using a Canvas. Is there a particular reason why you are setting the trasnform instead of each image's actual position via Canvas.SetLeft(imageName, posX) and Canvas.SetTop(imageName, posY)?

Cheers!
Kirupa :)

psychman
March 16th, 2009, 11:12 PM
Thanks Kirupa. No, I do not have a particular reason for using the transform vs. the actual postion. I tried using the actual position and it worked well, so thanks for the hint. I still have the same problem though with the images lining up in a diagonal line across the canvas and not in a random position on the canvas.

Another strange thing I noticed is that some of the images will stack up at the same location. The stacked images are never the same images, in the same location, but there are always small groups of images that stack up on top of eachother.

Here is how I changed the code to set the actual position: ("myImage" is a bitmap created within a foreach statment, so for each JPEG in a directory a "myImage" is created.)

Random myRandom1 = newRandom();
int rand1 = myRandom1.Next(1,400);
Canvas.SetLeft(myImage, rand1);
Canvas.SetTop(myImage, rand1);
myCanvas.Children.Add(myImage);

Thanks!

psychman
March 18th, 2009, 02:22 PM
Here is what worked for me:

Random myRandom1 = new Random();
int rand2 = myRandom1.Next(0,500);
int rand1 = myRandom1.Next(0,500);

myCanvas.Children.Add(myImage);

Canvas.SetLeft(myImage, rand1);
Canvas.SetTop(myImage, rand2);