我的窗口上有一个带有加载图片的Image控件(source是BitmapImage,stretch是Uniform)。我想对图像控件进行边框控制,相应地在源图像中设置帧坐标。
例如:
源图像高度:1500像素
源图像宽度:1000像素
第x帧:700像素
帧y:500像素
帧宽:100像素
帧高:150像素
我试过
var verticalRatio = this.ImageBitmap.ActualHeight / ((BitmapImage)this.ImageBitmap.Source).PixelHeight;
var horizontalRatio = this.ImageBitmap.ActualWidth / ((BitmapImage)this.ImageBitmap.Source).PixelWidth;
它似乎适用于Border的大小,但是Border会被移动。我认为这是因为图像显示图像缩放,图像在图像内部有一些余量。
我该怎么做才能解决这个问题?
由于
答案 0 :(得分:0)
我找到了答案。我计算当前Image控件的比率和移位,它使用Canvas控件放置在一个父容器中。我将此代码作为静态方法放在帮助器中:
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;
}
首先我计算比率:
ImageHelper.CalculateRatios(this.LayoutCanvas, (BitmapImage)this.ImageFingersBitmap.Source, ref _horizontalShift, ref _verticalShift, ref _horizontalRatio, ref _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);