0

I need to place a moveable rectangle on a WPF Image control. When the user clicks a button after moving the rectangle it should give me the Rect coordinates.

I can't imaging this is so hard to do, but I can't figure it out. Found some examples to draw a rectangle with the mouse and then crop the image, but that's not what I need.

Here is the code of my UserControl which can shown an Image and his properties. On the Image there should be placed a moveable rectangle as I described above.

Any ideas how I can accomplish this?

    <UserControl x:Class="Test.View.UserControls.PhotoEditorControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="500"
             d:DesignWidth="400"
             x:Name="photoEditorControl">
  <UserControl.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="../../Styles.xaml" />
      </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
  </UserControl.Resources>
  <Grid Background="Transparent"
        Visibility="{Binding ElementName=photoEditorControl,Path=ControlVisibility, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    <Grid Name="popupBackground"
          Grid.RowSpan="4">
      <Grid.Background>
        <SolidColorBrush Color="#9995AE"
                         Opacity="0.3" />
      </Grid.Background>
    </Grid>
    <Border BorderBrush="Black"
            Background="WhiteSmoke"
            BorderThickness="1"
            CornerRadius="15"
            DockPanel.Dock="Bottom"
            HorizontalAlignment="Center"
            VerticalAlignment="Center">
      <Border.BitmapEffect>
        <DropShadowBitmapEffect Color="Black"
                                Opacity="0.5"
                                Direction="270"
                                ShadowDepth="0.7" />
      </Border.BitmapEffect>
      <Grid Width="380"
            Height="450">
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="*" />
          <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="Auto" />
          <RowDefinition Height="*" />
          <RowDefinition Height="150" />
          <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Border Margin="15,15,15,0"
                Background="WhiteSmoke"
                Grid.Row="1"
                Grid.ColumnSpan="2"
                VerticalAlignment="Top"
                HorizontalAlignment="Center">
          <Border.Effect>
            <DropShadowEffect ShadowDepth="3"
                              Color="LightGray" />
          </Border.Effect>
          <Image Source="{Binding ElementName=photoEditorControl, Path=Image.MediumUrl, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                 Stretch="Uniform">
          </Image>
        </Border>
        <Grid Grid.Row="2"
              Grid.ColumnSpan="2">
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="150*" />
          </Grid.ColumnDefinitions>
          <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="25" />
          </Grid.RowDefinitions>
          <TextBlock Name="textBlock1"
                     Text="Properties"
                     Grid.ColumnSpan="2"
                     HorizontalAlignment="Center"
                     Style="{StaticResource InfoLabel}" />
          <TextBlock Grid.Row="1"
                     Name="textBlockName"
                     Text="Filename:"
                     Style="{StaticResource InfoLabel}" />
          <TextBlock Grid.Row="2"
                     Name="textBlockAlbum"
                     Text="Original name:"
                     Style="{StaticResource InfoLabel}" />
          <TextBlock Grid.Row="3"
                     Name="textBlockFilesize"
                     Text="Filesize:"
                     Style="{StaticResource InfoLabel}" />
          <TextBlock Grid.Row="4"
                     Name="textBlockSize"
                     Text="Size:"
                     Style="{StaticResource InfoLabel}" />
          <TextBlock Grid.Row="5"
                     Name="textBlockSavedDate"
                     Text="Upload date:"
                     Style="{StaticResource InfoLabel}" />
          <TextBlock Grid.Row="1"
                     Grid.Column="1"
                     Name="textBlockNameData"
                     Margin="4"
                     Text="{Binding ElementName=photoEditorControl, Path=Image.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
          <TextBlock Grid.Row="2"
                     Grid.Column="1"
                     Name="textBlockOriginalNameData"
                     Margin="4"
                     Text="{Binding ElementName=photoEditorControl, Path=Image.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
          <TextBlock Grid.Row="3"
                     Grid.Column="1"
                     Name="textBlockFileSizeData"
                     Margin="4"
                     Text="{Binding ElementName=photoEditorControl, Path=Image.FileSize, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
          <TextBlock Grid.Row="4"
                     Grid.Column="1"
                     Name="textBlockSizeData"
                     Margin="4">
              <TextBlock.Text>
                <MultiBinding StringFormat="{}{0}x{1}">
                  <Binding ElementName="photoEditorControl"
                           Path="Image.Width"
                           Mode="TwoWay"
                           UpdateSourceTrigger="PropertyChanged" />
                  <Binding ElementName="photoEditorControl"
                           Path="Image.Height"
                           Mode="TwoWay"
                           UpdateSourceTrigger="PropertyChanged" />
                </MultiBinding>
              </TextBlock.Text>
          </TextBlock>
          <TextBlock Grid.Row="5"
                     Grid.Column="1"
                     Name="textBlockUploadDateData"
                     Margin="4"
                     Text="{Binding ElementName=photoEditorControl, Path=Image.DateUploaded, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        </Grid>
        <Button Content="Close"
                Grid.Row="3"
                Height="30"
                HorizontalAlignment="Left"
                VerticalAlignment="Center"
                Margin="10 5 5 10"
                Name="buttonCancel"
                Width="75"
                Command="{Binding ElementName=photoEditorControl, Path=CloseControlCommand}" />
        <Button Content="Done"
                Grid.Column="1"
                Grid.Row="3"
                Height="30"
                Margin="5 5 10 10"
                HorizontalAlignment="Right"
                VerticalAlignment="Center"
                Name="buttonDone"
                Width="75"
                Visibility="Visible" />
      </Grid>
    </Border>
  </Grid>
</UserControl>

Why don I see my full UserControl code? When I vlick edit I do see it in the text editor.

2
  • Do you only need to know how to get the position of the rectangle, or do you need to move the rectangle as well?
    – Terry
    Commented Jun 19, 2013 at 15:07
  • @Djerry I need to be able to move the rectangle over the image to a place I want, inside the image that is. Commented Jun 19, 2013 at 15:33

2 Answers 2

1

XAML:

<Window x:Class="moveableRectangle.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Image Name="Image" Source="bsp.jpg" MouseMove="Image_MouseMove" MouseUp="Rectangle_MouseLeftButtonUp" />
    <Rectangle Name="Rect"  Width="100" Height="100" Fill="Transparent"  Stroke="Red" StrokeThickness="5" MouseLeftButtonDown="Rectangle_MouseLeftButtonDown" MouseLeftButtonUp="Rectangle_MouseLeftButtonUp"  />
</Grid>

Code behind:

 public partial class MainWindow : Window
{
    private bool moveRect;
    TranslateTransform trans = null;
    Point originalMousePosition;
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Rectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        moveRect = true;
        originalMousePosition = e.GetPosition(Image);
        Rect.IsHitTestVisible = false;

    }

    private void Image_MouseMove(object sender, MouseEventArgs e)
    {
        if (moveRect)
        {
            trans = Rect.RenderTransform as TranslateTransform;
            if (trans == null)
            {
                Rect.RenderTransformOrigin = new Point(0, 0);
                trans = new TranslateTransform();
                Rect.RenderTransform = trans;

            }
            trans.Y = -(originalMousePosition.Y - e.GetPosition(Image).Y);
            trans.X = -(originalMousePosition.X - e.GetPosition(Image).X);
        }
        e.Handled = false;
    }

    private void Rectangle_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        moveRect = false;
        Rect.IsHitTestVisible = true;
    }


}
2
  • That does what I need it to do. Only 2 questions. How can I avoind the retangle being dragged outside the image boundries (outside the grid)? I mean that when the top of the rectangle hits the top of the image it should stop moving. Second, in the Rectangle_MouseLeftButtonUp event the Rect object's _rect property holds the coordinates of the rectangle on the image, correct? Thx! Commented Jun 19, 2013 at 15:58
  • You could change the Grid to a Canvas, and then work with the Canvas.Top, Canvas.Left, etc... Properties. This would give you the Rect coordinates and you could prevent the XY coordinates of the Rect to be larger than the Canvas
    – Ketobomb
    Commented Jun 20, 2013 at 6:57
0

I used this simple XAML:

<Grid Name="grdBoard">
    <Image Source="http://lorempixel.com/400/200/sports/" />
    <Rectangle Name="rctRectangle" Fill="Transparent" Stroke="Yellow" StrokeThickness="2" Width="50" Height="50" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</Grid>
<Button Content="Get the coordinates" Name="btnGetCoordinates"/>
<TextBlock Name="txtOutput" />

This is the code that moves the rectangle. At any time, by clicking the button, you can get the position of the rectangle by getting the margin:

public partial class MainWindow : Window
{
    bool IsMouseDown;

    public MainWindow()
    {
        InitializeComponent();
        rctRectangle.MouseLeftButtonDown += StartMoveRectangle;
        rctRectangle.MouseLeftButtonUp += EndMoveRectangle;
        rctRectangle.MouseMove += MoveRectangle;
    }

    private void GetCoordinates()
    {
        Thickness margin = rctRectangle.Margin;
        double x = margin.Left;
        double y = margin.Top;
        WriteToOutput("Coordinates are: X = " + x + " and Y = " + y);
    }

    private void StartMoveRectangle(object sender, EventArgs e) 
    {
        IsMouseDown = true;
    }

    private void MoveRectangle(object sender, MouseEventArgs e)
    {
        if (IsMouseDown)
        {
            Point cursorposition = e.GetPosition(grdBoard);
            rctRectangle.Margin = new Thickness(cursorposition.X - (rctRectangle.Width / 2), cursorposition.Y - (rctRectangle.Height / 2), 0, 0);
        }
    }

    private void EndMoveRectangle(object sender, EventArgs e)
    {
        IsMouseDown = false;
    }

    private void WriteToOutput(string text)
    {
        txtOutput.Text = text;
    }
}

Let me know if this is what you were trying for.

2
  • Thanks for your effort! But I'm more looking at a C# solution. Commented Jun 19, 2013 at 15:59
  • @PitAttack76: I've changed my example. In the future, indicate which language you want answers in by providing the tag in your question. That prevents people from having to create two solutions for you.
    – Terry
    Commented Jun 20, 2013 at 7:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.