0

我想计算 BorderControl 到添加它的 Grid 的距离,但以四舍五入的百分比表示。

我使用这种方法:

internal static tPosition GetControlTPosition(Border tempInnerControl, Grid tempOuterGrid)
    {
        tPosition tempTPosition = new tPosition();

        Point tempInnerControlCornerPoint = tempInnerControl.PointToScreen(new Point(0, 0));

        Point tempOuterGridCornerPoint = tempOuterGrid.PointToScreen(new Point(0, 0));

        //
        //Top Left Corner
        //Fist we calculate the Distance of the Top left Corners of both elements
        double distanceLeft = tempInnerControlCornerPoint.X - tempOuterGridCornerPoint.X;
        double distanceTop = tempInnerControlCornerPoint.Y - tempOuterGridCornerPoint.Y;

        //Then we set the percentage of our position accordingly
        tempTPosition.PositionLeft = (int)(((distanceLeft) * 100 / tempOuterGrid.ActualWidth));
        tempTPosition.PositionTop = (int)((distanceTop) * 100 / tempOuterGrid.ActualHeight);

        //
        // Bottom Right Corner
        //Now we calculate the distance of the bottom right corner to the outher grids bottom right corner
        double distanceRight =  (tempOuterGridCornerPoint.X + tempOuterGrid.ActualWidth) - (tempInnerControlCornerPoint.X + tempInnerControl.ActualWidth);
        double distanceBottom = (tempOuterGridCornerPoint.Y + tempOuterGrid.ActualHeight) - (tempInnerControlCornerPoint.Y + tempInnerControl.ActualHeight);

        tempTPosition.PositionRight = (int)((distanceRight)*100/tempOuterGrid.ActualWidth);
        tempTPosition.PositionBottom = (int)((distanceBottom) * 100 / tempOuterGrid.ActualHeight);

        return tempTPosition;
    }

我的问题是 BorderControl 不断变大,这意味着百分比过低存在问题,我想这是因为我失去了精度。我怎样才能避免这种情况?

由于各种原因,我需要将数字作为整数。

tPosition 只是 left,top,right,bottom 作为整数

4

1 回答 1

1

在查找 tempTPosition 时,您很可能会失去精度,而不是像您使用 int 那样使用 double,这会将值四舍五入为整数

双打试试

//Then we set the percentage of our position accordingly
    tempTPosition.PositionLeft = (double)(((distanceLeft) * 100 / tempOuterGrid.ActualWidth));
    tempTPosition.PositionTop = (double)((distanceTop) * 100 / tempOuterGrid.ActualHeight);

请记住对 PositionRight 和 PositionBottom 也执行此操作

于 2013-06-19T12:30:11.380 回答