使用RotateTransform时无效的强制转换异常

时间:2012-04-26 11:58:17

标签: c# windows-phone-7 xaml

为什么下面的代码行导致{“InvalidCastException”}

((RotateTransform)image.RenderTransform).Angle = 90; 

方法中的整个代码是

void loadImage()
        {
            // The image will be read from isolated storage into the following byte array

        byte[] data;

        // Read the entire image in one go into a byte array

        using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
        {

            // Open the file - error handling omitted for brevity

            // Note: If the image does not exist in isolated storage the following exception will be generated:

            // System.IO.IsolatedStorage.IsolatedStorageException was unhandled 

            // Message=Operation not permitted on IsolatedStorageFileStream 

            using (IsolatedStorageFileStream isfs = isf.OpenFile("0.jpg", FileMode.Open, FileAccess.Read))
            {

                // Allocate an array large enough for the entire file

                data = new byte[isfs.Length];



                // Read the entire file and then close it

                isfs.Read(data, 0, data.Length);

                isfs.Close();

            }
        }



        // Create memory stream and bitmap

        MemoryStream ms = new MemoryStream(data);

        BitmapImage bi = new BitmapImage();

        // Set bitmap source to memory stream

        bi.SetSource(ms);

        // Create an image UI element – Note: this could be declared in the XAML instead

        Image image = new Image();

        // Set size of image to bitmap size for this demonstration

        image.Height = bi.PixelHeight;

        image.Width = bi.PixelWidth;

        // Assign the bitmap image to the image’s source

        image.Source = bi;

        ((RotateTransform)image.RenderTransform).Angle += 90; 

        // Add the image to the grid in order to display the bit map

        ContentPanelx.Children.Add(image);

    }

编辑

更改了以下代码后,它不会崩溃,但不会绘制图像。

        image.Height = bi.PixelHeight;

        image.Width = bi.PixelWidth;

        // Assign the bitmap image to the image’s source

        image.Source = bi;
        image.RenderTransform = new RotateTransform() { Angle = 90 };

        ContentPanelx.Children.Add(image);

我缺少一个步骤吗?

非常感谢, -code

3 个答案:

答案 0 :(得分:2)

您刚刚创建了一个图像对象。其RenderTransform属性未引用RotateTransform实例。尝试:image.RenderTransform = new RotateTransform(){Angle=90};

答案 1 :(得分:0)

在一个简单的答案级别,看起来你实际上并没有真正指定RenderTransform来包含RotateTransform - 所以演员阵容失败也就不足为奇了。

作为更完整的答案:

  • 如果您尝试从文件中旋转图像,那么最好使用像http://writeablebitmapex.codeplex.com/这样的库在代码中为您执行此操作,而不是在UI元素中执行此操作。
  • 或者如果您确实要将旋转应用于UI元素,则可以使用以下代码:

image.RenderTransform = new RotateTransform() {Angle = 45.0};

答案 2 :(得分:0)

RenderTransform属性的默认值为Transform.Identity。您必须先将RotateTransform应用到Image,然后再进行操作。

image.RenderTransform = new RotateTransform();