سؤال

I am trying to draw an image in a Windows Store app. The image is predrawn in the XAML designer interface.

When clicking on a button, I want it's X and Y coördinates to change randomly; taking the screensize into account.

Googling and trying did get me somewhere. Problem is, however, that the image sometimes disappears off the screen (why I do not know).

How can I change the X and Y position so that the image does not fall off the screen?

What I have tried (some variations too):

var bounds = Window.Current.Bounds;
Random r = new Random();
int y = r.Next(0, (int)bounds.Right);
int x = r.Next(140, (int)bounds.Bottom);
image.Margin = new Thickness(x, y, 0,0);

For reference: The 140 value is the position from the top that the image can not be displayed in.

I know the Thickness-class uses "Left, Top, Right, Bottom" positioning. I am unsure how to randomly calculate the correct values.

هل كانت مفيدة؟

المحلول

You swapped your x and y values. Assuming your image is in a panel the size of the window and has VerticalAlignment="Top" and HorizontalAlignment="Left" you could do this:

var bounds = Window.Current.Bounds;
var r = new Random();
int x = r.Next(0, (int)bounds.Right - (int)image.ActualWidth);
int y = r.Next(140, (int)bounds.Bottom - (int)image.ActualHeight);
image.Margin = new Thickness(x, y, -x, -y);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top