0

我正在使用代码来缩放和平移我的图像控件。

我想知道如何将控件恢复到原始状态。

在用户决定改变图片后,图像框必须恢复到原来的位置和状态,这样他/她才能开始正确和新鲜地缩放。

我尝试使用这样的东西,但仍然没有运气:

Image OriginalPic;
...
...
InitializeComponents();
OriginalPic = MainPic;
...
...
void ChangePic(){
MainPic = OriginalPic; // Doesn't work :(
...
}
4

3 回答 3

0

从您提供的小代码中,我假设两者都MainPicOriginalPic引用同一个对象-> 对一个引用的更改也会影响另一个引用。您实际上需要创建一个包含原始信息的备份图片,您需要创建一个deep copy您的图片。

参考这篇文章:

public static T DeepClone<T>(T obj)
{
 using (var ms = new MemoryStream())
 {
   var formatter = new BinaryFormatter();
   formatter.Serialize(ms, obj);
   ms.Position = 0;

   return (T) formatter.Deserialize(ms);
 }
}

这将创建您的深层副本,Image您可以使用它来将图像恢复到其原始状态。


ICloneable此外,我还找到了使用-Interface的教程:

要获得对象的深层副本,您必须为 Invoice 及其所有相关类实现 IClonable 接口:

public class Invoice: IClonable
{
 public int No;
 public DateTime Date;
 public Person Customer;
 //.............

 public object Clone()
 {
 Invoice myInvoice = (Invoice)this.MemberwiseClone();
 myInvoice.Customer = (Person) this.Customer.Clone();
 return myInvoice;
 }
}

public class Person: IClonable
{
 public string Name;
 public int Age;

 public object Clone()
 {
 return this.MemberwiseClone();
 }
}

编辑

似乎System.Windows.Controls.Image无法序列化......您可以尝试从中派生并实现ISerializable或创建(static)方法并手动创建克隆。然而,这些步骤中的任何一个都是必要的!

于 2013-05-11T20:23:55.570 回答
0

更改OriginalPic = MainPic;为:OriginalPic = MainPic.Clone();

于 2013-05-11T20:24:17.697 回答
0

好的,我尝试了很多方法来深度复制图像控件。但似乎没有可以开箱即用的功能。但是bash.d有一个想法。

  • 尝试使用 XamplWriter 和 XamlReader。
  • 深度复制它的父对象也不起作用。
  • 尝试使用应该适用于任何对象的ObjectExtensions.cs 。

这是我为还原转换所做的操作:

void ResetTransformationOfImage()
        {
            TransformGroup group = new TransformGroup();

            ScaleTransform xform = new ScaleTransform();
            group.Children.Add(xform);

            TranslateTransform tt = new TranslateTransform();
            group.Children.Add(tt);

            MainPic.RenderTransform = group;
        }

无论如何,我期待着看看是否有人可以实现这样的复制功能并将其标记为真正的答案,即使我的问题现在已经解决了。

谢谢。

于 2013-05-11T22:53:02.227 回答