C# 将图片坐标转换为画布坐标
我有一个图像控件,在我的窗口上加载了图片(源是BitmapImage,拉伸是统一的)。我想把边界控制放在源图像中相应的帧坐标上 例如: 源图像高度:1500像素 源图像宽度:1000像素 帧x:700像素 帧y:500像素 帧宽:100像素 帧高:150像素 我试过了C# 将图片坐标转换为画布坐标,c#,wpf,coordinates,C#,Wpf,Coordinates,我有一个图像控件,在我的窗口上加载了图片(源是BitmapImage,拉伸是统一的)。我想把边界控制放在源图像中相应的帧坐标上 例如: 源图像高度:1500像素 源图像宽度:1000像素 帧x:700像素 帧y:500像素 帧宽:100像素 帧高:150像素 我试过了 var verticalRatio = this.ImageBitmap.ActualHeight / ((BitmapImage)this.ImageBitmap.Source).PixelHeight; var horizon
var verticalRatio = this.ImageBitmap.ActualHeight / ((BitmapImage)this.ImageBitmap.Source).PixelHeight;
var horizontalRatio = this.ImageBitmap.ActualWidth / ((BitmapImage)this.ImageBitmap.Source).PixelWidth;
看起来它适用于边界的大小,但边界被移动了。我认为这是因为图像显示图片缩放,图片内部有一些空白
我应该做什么来解决这个问题
谢谢,我找到答案了。我计算当前图像控件的比率和移位,该控件放置在一个带有画布控件的父容器中。我将此代码作为静态方法放置在helper中:
public static void CalculateRatios(Panel panel, BitmapImage image, ref double horizontalShift, ref double verticalShift, ref double horizontalRatio, ref double verticalRatio)
{
panel.UpdateLayout();
var ratioSource = image.PixelWidth / image.PixelHeight;
var ratioImage = panel.ActualWidth / panel.ActualHeight;
Size pictureInControlSize;
if (ratioSource > ratioImage) // image control extended in height
{
pictureInControlSize = new Size(panel.ActualWidth, panel.ActualWidth / ratioSource);
}
else if (ratioSource < ratioImage) // image control extended in width
{
pictureInControlSize = new Size(panel.ActualHeight * ratioSource, panel.ActualHeight);
}
else // image control have the same proportions
{
pictureInControlSize = new Size(panel.ActualWidth, panel.ActualHeight);
}
horizontalShift = (panel.ActualWidth - pictureInControlSize.Width) / 2d;
verticalShift = (panel.ActualHeight - pictureInControlSize.Height) / 2d;
horizontalRatio = pictureInControlSize.Width / image.PixelWidth;
verticalRatio = pictureInControlSize.Height / image.PixelHeight;
}
然后我用它来计算边框的大小和位置:
Width = box.Size.Width * _horizontalRatio,
Height = box.Size.Height * _verticalRatio,
Canvas.SetLeft(contentControl, _horizontalShift + box.TopLeft.X * _horizontalRatio);
Canvas.SetTop(contentControl, _verticalShift + box.TopLeft.Y * _verticalRatio);
Width = box.Size.Width * _horizontalRatio,
Height = box.Size.Height * _verticalRatio,
Canvas.SetLeft(contentControl, _horizontalShift + box.TopLeft.X * _horizontalRatio);
Canvas.SetTop(contentControl, _verticalShift + box.TopLeft.Y * _verticalRatio);