简体   繁体   中英

Converting an objects x/y value into an int

I have a simply block of code, that when you mouse up, it snaps an object to the nearest 30/30 grid.

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    int gridCubeWidth = 30;
    int gridCubeHeight = 30;

    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {                                       
        double newX = Math.Round(pictureBox1.Left / (double)gridCubeWidth) * 
            (double)gridCubeWidth;

        pictureBox1.Left = (int)newX;

        double newY = Math.Round(pictureBox1.Top / (double)gridCubeHeight) * 
            (double)gridCubeHeight;

        pictureBox1.Top = (int)newY;
    }
}

This is the only way I managed to get this to work, because from what I can tell, pictureBox1.left/top are in the form of "Doubles", which breaks my Math.Round.

I've tried changing everything to be Int, and adding (Int) in front of the pictureBox1.Left, but it doesn't seem to change this.

int newX = Math.Round((int)pictureBox1.Left / gridCubeWidth) * gridCubeWidth;
pictureBox1.Left = newX;

I feel like what I'm doing is somewhat very redundant, converting everything to Doubles, then back to an Int, and that there'd be a much simpler way to achieve this.

My main question, is why doesn't (int)pictureBox1.Left seem to convert this value into an Int

The Left and Top properties are ints. I don't see why you need doubles. See here: https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.left?view=netframework-4.8

You should be able to do rounding like this: int left = (pictureBox1.Left / 30) * 30;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM