【问题标题】:Converting picture coordunates to canvas coordinates将图片坐标转换为画布坐标
【发布时间】:2014-03-12 12:22:33
【问题描述】:

我的窗口上有一个带有加载图片的图像控件(源是 BitmapImage,拉伸是 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 被移动了。我认为这是因为 Image 显示图片缩放并且图片在 Image 内有一些边距。

我应该怎么做才能解决这个问题?

谢谢

【问题讨论】:

    标签: c# wpf coordinates


    【解决方案1】:

    我找到了答案。我计算当前 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);
    

    【讨论】:

      猜你喜欢
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      • 2015-03-13
      • 2013-09-01
      • 2019-08-24
      • 1970-01-01
      相关资源
      最近更新 更多