Windows Phone 7 Silverlight: How to move an image

by sunil ravulapalli /30. March 2010 04:17 /windows-phone /Comments (0)

To do this you will need a Canvas in the "ContentGrid" in the MainPage.xaml. Also make sure you have ManipulationStarted, ManipulationDelta activated on the content grid as show below.

 

In MainPage.xaml.cs,

public partial class MainPage : PhoneApplicationPage
{
    Image img;
    double startingPositionOfImageX;
    double startingPositionOfImageY;


    public MainPage()
    {
        InitializeComponent();

        SupportedOrientations = SupportedPageOrientation.Portrait | 
                SupportedPageOrientation.Landscape;

        img = new Image();

        img.Name = "myimg";
        //Size the Image
        img.Height = 80;
        img.Width = 80;

        //Place it top left
        img.HorizontalAlignment = HorizontalAlignment.Left;
        img.VerticalAlignment = VerticalAlignment.Top;

        //Point at the physical file
        Uri uri = new Uri("1.JPG", UriKind.Relative);
        ImageSource imgsource = new 
        System.Windows.Media.Imaging.BitmapImage(uri);

        //Set image property
        img.SetValue(Image.SourceProperty, imgsource);
        img.SetValue(Canvas.TopProperty, 100.0);
        img.SetValue(Canvas.LeftProperty, 100.0);

        canvas1.Children.Add(img);
    }

    private void ContentGrid_ManipulationStarted(object sender, 
                                           ManipulationStartedEventArgs e)
    {
        if (e.OriginalSource == img)
        {
            startingPositionOfImageX = 
            Convert.ToDouble(img.GetValue(Canvas.LeftProperty));
             
            startingPositionOfImageY =
            Convert.ToDouble(img.GetValue(Canvas.TopProperty));
        }
    }

    private void ContentGrid_ManipulationDelta(object sender, 
                                         ManipulationDeltaEventArgs e)
    {
        if (e.OriginalSource == img)
        {
            img.SetValue(Canvas.LeftProperty, 
            e.CumulativeManipulation.Translation.X + startingPositionOfImageX);
                
            img.SetValue(Canvas.TopProperty,
            e.CumulativeManipulation.Translation.Y + startingPositionOfImageY);
        }
    }

}
blog comments powered by Disqus