使用ManipulationDelta事件在C#中生成图像控件

时间:2012-12-17 02:51:48

标签: c# image xaml windows-runtime

我在处理事件时遇到问题。基本上程序生成图像但具有相同的事件。

 private Image MakeImage(string filename)
 {
     Uri uri = new Uri("ms-appx:///CategoryData/" + filename+".png");
     BitmapImage bitmap = new BitmapImage(uri);
     Image image = new Image()
     {
         Height = 100,
         Width = 100,
         Stretch = Stretch.Uniform,
         MaxHeight = 250,
         MaxWidth  = 250,
         HorizontalAlignment = HorizontalAlignment.Left,
         VerticalAlignment = VerticalAlignment.Top,
         Name = filename+"Img",
         ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY,
     };
     image.Source = bitmap;
     image.ManipulationDelta += image_ManipulationDelta;
     return image;
 }

 void image_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
 {
     Image image = sender as Image;
     CompositeTransform ct = image.RenderTransform as CompositeTransform;
     ct.TranslateX += e.Delta.Translation.X;
     ct.TranslateY += e.Delta.Translation.Y;
     //throw new NotImplementedException();
 }

并在“ct.TranslateX += e.Delta.Translation.X;”上发生异常。 对象引用未设置为对象的实例。

1 个答案:

答案 0 :(得分:1)

检查您的演员阵容CompositeTransform,因为可能是错误的类型 - 导致ct成为null,因此进入您的例外。

编辑:添加了一个例子。

CompositeTransform ct = image.RenderTransform as CompositeTransform;
if (ct == null) image.RenderTransform = ct = new CompositeTransform();
ct.TranslateX += e.Delta.Translation.X;
ct.TranslateY += e.Delta.Translation.Y;

此外,如果您只需要翻译图像,为什么不使用TranslateTransform