GetPosition使用Image元素返回错误的值

时间:2014-12-29 17:35:17

标签: c# wpf image

我写了WPF应用程序。有Image个元素,我定义了MouseDown个事件。

private void firstImagePanel_MouseDown_1(object sender, MouseButtonEventArgs e)
    {
        Point x = e.GetPosition(firstImagePanel);
        MessageBox.Show(string.Format("X:\t{0}\nY:\t{1}",x.X/image.PixelWidth, x.Y/image.PixelHeight));
    }

image - 是此面板的来源。 当我单击图像上的某个位置时,MessageBox.Show()会写错位置。 例如,当我点击中心时,它写道: X: 0.25 Y: 0.25 我不知道错误在哪里。

XAML:

<Window x:Class="Blending.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>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition/>
    </Grid.RowDefinitions>

    <StackPanel Grid.Column="0" Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Center">
        <Button x:Name="openFirstImage" Content="Open 1st image" Padding="10" Margin="0 10 0 0" Click="openFirstButton_Click"/>
        <Button x:Name="dragAndDrop"  Content="Drag and Drop" Padding="10" Margin="10 10 0 0" Click="dragAndDrop_Click"/>
    </StackPanel>

    <StackPanel Grid.Column="1" Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Center">
        <Button x:Name="openSecondImage" Content="Open 2nd image" Padding="10" Margin="0 10 0 0" Click="openSecondImage_Click"/>
        <Button x:Name="blend"  Content="Blend" Padding="10" Margin="10 10 0 0" Click="blend_Click"/>
    </StackPanel>

    <Image  x:Name="firstImagePanel" VerticalAlignment="Top" Grid.Column="0" Grid.Row="1" Margin="3,0" MouseDown="firstImagePanel_MouseDown_1" />
    <Image  x:Name="secondImagePanel" VerticalAlignment="Top" Grid.Column="1" Grid.Row="1" Margin="3"/>
</Grid>

我注意到,对于不同的图片,位置有不同的比例。

1 个答案:

答案 0 :(得分:0)

试试这个:

<Image x:Name="firstImagePanel"
       Source="http://ia.media-imdb.com/images/M/MV5BMjcwNzczNDQ0MV5BMl5BanBnXkFtZTcwMTE0NzA0MQ@@._V1_SX214_AL_.jpg"
       VerticalAlignment="Top"
       MouseDown="FirstImagePanel_OnMouseDown" />

和事件处理程序:

Point x = e.GetPosition(firstImagePanel);
MessageBox.Show(string.Format("X:\t{0}\nY:\t{1}", 

    x.X / firstImagePanel.ActualWidth, 
    x.Y / firstImagePanel.ActualHeight));

问题可能是您有保证金,或者您的PixelWidth不等于屏幕上显示的图片。

如果你点击居中,我的例子应该给你0.5,0.5。