用裁剪的BitmapSource替换Image

时间:2012-01-27 15:08:18

标签: c# wpf image xaml

我的wpf控件上有一个Image 而我正试图生成它的一部分 - 这或多或少都可以。 我使用了一个codeproject解决方案来生成croped图像的BitmapSource(http://www.codeproject.com/KB/WPF/CropAdorner.aspx)但是当我试图 用生成的BitmapSource替换当前图像,如下所示

imgCurrent.Source = generatedBitmapSource; 

我看到非常奇怪的行为(( 我需要一个建议如何使用基于BitmapSource的new更改当前图像。

我的XAML(没有什么特别的 - 通过右键单击我试图用croped替换currentImage):

<DockPanel Height="395" Width="926">
    <!--Went with a DockPanel here so that the image would always be centered in its parent control.-->
    <Image x:Name="imgCurrent" VerticalAlignment="Center" HorizontalAlignment="Center" MouseRightButtonDown="imgCurrent_MouseRightButtonDown"/>
</DockPanel> 

右键点击:

  private void imgCurrent_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    { 
           generatedBitmapSource = _clp.BpsCrop();
           //this clears croping adonder
           AdornerLayer aly = AdornerLayer.GetAdornerLayer(_felCur);
           aly.Remove(_clp);
    //
       imageCurrent.Source = generatedBitmapSource;
    }

裁剪方法(来自codeproject):

public BitmapSource BpsCrop()
        {
            Thickness margin = AdornerMargin();
            Rect rcInterior = _prCropMask.RectInterior;

            Point pxFromSize = UnitsToPx(rcInterior.Width, rcInterior.Height);

            // It appears that CroppedBitmap indexes from the upper left of the margin whereas RenderTargetBitmap renders the
            // control exclusive of the margin.  Hence our need to take the margins into account here...

            Point pxFromPos = UnitsToPx(rcInterior.Left + margin.Left, rcInterior.Top + margin.Top);
            Point pxWhole = UnitsToPx(AdornedElement.RenderSize.Width + margin.Left, AdornedElement.RenderSize.Height + margin.Left);
            pxFromSize.X = Math.Max(Math.Min(pxWhole.X - pxFromPos.X, pxFromSize.X), 0);
            pxFromSize.Y = Math.Max(Math.Min(pxWhole.Y - pxFromPos.Y, pxFromSize.Y), 0);
            if (pxFromSize.X == 0 || pxFromSize.Y == 0)
            {
                return null;
            }
            System.Windows.Int32Rect rcFrom = new System.Windows.Int32Rect(pxFromPos.X, pxFromPos.Y, pxFromSize.X, pxFromSize.Y);

            RenderTargetBitmap rtb = new RenderTargetBitmap(pxWhole.X, pxWhole.Y, s_dpiX, s_dpiY, PixelFormats.Default);
            rtb.Render(AdornedElement);
            return new CroppedBitmap(rtb, rcFrom);
        }

1 个答案:

答案 0 :(得分:0)

你确定你的“BitmapSource of croped image”没有问题吗?您是否可以进行测试,将其替换为另一个有效的Bitmap,并尝试它是否有效。如果它适用于另一个,但不是“BitmapSource of croped image”,那么你可能会遇到创建“BitmapSource of croped image”的问题。