2

我需要在 DrawingVisual 中显示图像源的裁剪区域,但在过去的几个小时里,我只是为应该是一项简单的任务绘制了空白。

我的计划是实现定时动画(用于 HMI 系统),它将拍摄包含各种帧的大图像。根据状态变量,DrawingVisual 将从这个大图像中提取要显示的当前帧 - 因此需要裁剪。

我的代码如下:

int width = Convert.ToInt32(_imageSource.Width / 2);
            int height = Convert.ToInt32(_imageSource.Height);
            BitmapImage bm = _imageSource.Clone() as BitmapImage;              

            bm.BaseUri = BaseUriHelper.GetBaseUri(this);
            CroppedBitmap c = new CroppedBitmap(bm, new Int32Rect(0, 0, width, height));
            ImageDrawing id = new ImageDrawing(c, new Rect(0, 0, width, height));
            dg.Children.Add(id);
            dc.DrawDrawing(dg);

但是,在创建裁剪图像后,我收到

“值不在预期范围内”

顺便说一句,该图像是在资源字典(在当前程序集中)中加载的 png 为

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<BitmapImage x:Key="elbowSmallBlueBL" UriSource="./Assets/HMI/Elbows/Small/Elbow Blue BottomLeft.png" />

然后使用 (ImageSource)FindResource("...

首先,我不理解错误消息,在任何地方都找不到令人满意的解释,其次,为什么执行一个简单的任务这么难?

谢谢你的帮助。

ps 我认为这是由于无法找到资源。但是,如果原始图像源很好,为什么克隆版本的行为会有所不同?pps 删除“bm.BaseUri = ...”行会导致相同的错误。

为了简化事情,我创建了一个测试项目,它只有一个按钮,单击时会尝试创建 CroppedBitmap。

按钮点击 =

 private void Button_Click(object sender, RoutedEventArgs e)
    {

        BitmapSource i = (BitmapSource)FindResource("elbowSmallBlueBL");
        try
        {
            CroppedBitmap c = new CroppedBitmap(i, new Int32Rect(0, 0, 100, 100));
        }
        catch (Exception ex)
        {
        }
    }
}

资源字典引用位图:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- Elbows -->
<BitmapImage x:Key="elbowSmallBlueBL" UriSource="./Assets/HMI/Elbows/Small/Elbow Blue BottomLeft.png" />

并包含 App.xaml

    <Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>

            <ResourceDictionary Source="rdHMIControls.xaml" />

BitmapSource (i) 有效并且对 CroppedBitmap 的调用会引发 ArgumentException,“值不在可接受的范围内”。

创建或尝试创建裁剪图像肯定不会比这更简单吗?

另一个我从 MSDN 上取下的例子

       BitmapSource i = (BitmapSource)this.FindResource("test");
        try
        {

            // Create an Image element.
            Image croppedImage = new Image();
            croppedImage.Width = 200;
            croppedImage.Margin = new Thickness(5);


            // Create a CroppedBitmap based off of a xaml defined resource.
            CroppedBitmap cb = new CroppedBitmap(
               i,
               new Int32Rect(30, 20, 105, 50));       //select region rect
            croppedImage.Source = cb;                 //set image source to cropped

新的 CroppedBitmap 再次抛出 InvalidArgument 异常

有什么想法吗?

谢谢

4

0 回答 0