Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当图片大于矩形时,计算图片裁剪的矩形坐标_C#_Wpf_Math_Coordinates_Crop - Fatal编程技术网

C# 当图片大于矩形时,计算图片裁剪的矩形坐标

C# 当图片大于矩形时,计算图片裁剪的矩形坐标,c#,wpf,math,coordinates,crop,C#,Wpf,Math,Coordinates,Crop,我正在开发自己的图片查看器,并正在创建一种图像裁剪方法。它确实适用于我当前的代码。但是,应用程序正在动态调整图像大小以适应用户的屏幕。因此,调整大小时,计算的图像X.Y坐标不正确。我的数学不是很好,所以我不知道怎么计算 这是我正在使用的代码 internal static Int32Rect GetCrop() { var cropArea = cropppingTool.CropTool.CropService.GetCroppedArea();

我正在开发自己的图片查看器,并正在创建一种图像裁剪方法。它确实适用于我当前的代码。但是,应用程序正在动态调整图像大小以适应用户的屏幕。因此,调整大小时,计算的图像X.Y坐标不正确。我的数学不是很好,所以我不知道怎么计算

这是我正在使用的代码

    internal static Int32Rect GetCrop()
    {
        var cropArea = cropppingTool.CropTool.CropService.GetCroppedArea();
        var x = Convert.ToInt32(cropArea.CroppedRectAbsolute.X);
        var y = Convert.ToInt32(cropArea.CroppedRectAbsolute.Y);
        var width = Convert.ToInt32(cropArea.CroppedRectAbsolute.Width);
        var height = Convert.ToInt32(cropArea.CroppedRectAbsolute.Height);

        return new Int32Rect(x, y, width, height);
    }
cropera
变量来自我自己的修改版本。它是一个
Rect
,从用户绘制的正方形返回X和Y坐标以及宽度和高度,用于选择图像的裁剪区域

我有用于调整图像宽度和高度的变量,以及图像的原始像素宽度和像素高度。裁剪UI使用调整大小的变量,以适合用户的屏幕

为清晰起见,图像大小按此方式计算,图像控制设置为Stretch.Fill

    double width = sourceBitmap.PixelWidth;
    double height = sourceBitmap.PixelHeight;
    double maxWidth = Math.Min(SystemParameters.PrimaryScreenWidth - 300, width);
    double maxHeight = Math.Min(SystemParameters.PrimaryScreenHeight - 300, height);

    var aspectRatio = Math.Min(maxWidth / width, maxHeight / height);
    width *= aspectRatio;
    height *= aspectRatio;

    image.Width = width;
    image.Height = height;

所以问题是,如何计算渲染大小和实际像素大小之间的偏移量?

如果我理解这一点:您已经计算了一个名为
aspectRatio
的比率,以将图像从其实际大小缩放到屏幕大小。您有一个裁剪工具,该工具根据缩放尺寸图像提供坐标,您希望转换这些坐标,以便将其应用于图像的原始尺寸

假设以上是正确的,这应该很简单

如果按以下公式计算缩放高度和宽度:

scaledWidth = originalWidth * ratio
scaledHeigth = originalHeigth * ratio
然后,您可以通过除法来反转乘法:

originalWidth = scaledWidth / ratio
originalHeight = scaledHeight / ratio
这也适用于图像中的任何坐标。可以从缩放图像中获取坐标,并将其转换为原始图像的坐标,如下所示:

originalX = scaledRect.X / ratio
originalY = scaledRect.Y / ratio
originalWidth = scaledRect.Width / ratio
originalHeight = scaledRect.Height / ratio
您必须小心确保
scaledRect
的值都不是
0
,因为除法和0不会混合。缩放坐标中的
0
值也将转换为原始坐标空间中的
0
,因此
0
应保持
0
。您可以使用
if
语句执行此操作