【问题标题】:Calculate coordinates rectangle for picture cropping, when picture bigger than rectangle当图片大于矩形时,计算图片裁剪的坐标矩形
【发布时间】:2020-06-15 20:48:21
【问题描述】:

我正在开发自己的图片查看器,并且正在创建图像裁剪方法。它确实适用于我当前的代码。但是,应用程序会动态调整图像大小以适应用户的屏幕。所以当它调整大小时,计算出来的图像的 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);
    }

cropArea 变量来自我自己修改后的https://github.com/dmitryshelamov/UI-Cropping-Image 版本。它是一个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;

那么问题来了,如何计算渲染大小和实际像素大小之间的偏移量?

【问题讨论】:

    标签: c# wpf math coordinates crop


    【解决方案1】:

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

    假设上面是对的,这应该很简单。

    如果缩放后​​的高度和宽度通过以下方式计算:

    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 语句来做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多