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

问题描述 投票:0回答:1

我正在开发自己的图片查看器,并且正在创建图像裁剪方法。它确实适用于我当前的代码。但是,该应用程序正在动态调整图像的大小以适合用户的屏幕。因此,调整大小时,图像的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坐标以及宽度和高度,用于选择图像的裁剪区域。

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

为了清楚起见,图像尺寸是照此计算的,并且图像控件设置为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个回答
0
投票

如果我理解这一点:您已经计算出一个名为aspectRatio的比例,以将图像从实际尺寸缩放到屏幕尺寸。您有一个裁剪工具,可以根据scaled大小的图像为您提供坐标,并且您想要转换这些坐标,以便可以将它们应用于图像的original大小。

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

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

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语句执行此操作。

© www.soinside.com 2019 - 2024. All rights reserved.