我正在试图弄清楚如何限制平移以使图像完全保持在其包含边界的范围内。对此方面的任何帮助将不胜感激。感谢....
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MapTest.Window1"
Title="PanTest"
Width="484"
Height="400"
WindowStartupLocation="CenterScreen">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Margin="8,8,8,0"
TextWrapping="Wrap">
To pan the image, simply click on it then drag. I'd like to
constrain the pan so that the image remains entirely within
the border, but without resorting to ClipToBounds. Any help
in this regard would be greatly appreciated. Thanks....</TextBlock>
<Border x:Name="border"
Margin="8"
BorderBrush="Black"
BorderThickness="1"
Grid.Row="1">
<Image x:Name="image"
Source="Penguins.jpg"
Opacity="1"
Width="300"
Height="300"
Stretch="Uniform"
RenderTransformOrigin="0.5,0.5" />
</Border>
</Grid>
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
namespace MapTest
{
public partial class Window1 : Window
{
private Point origin;
private Point start;
public Window1()
{
InitializeComponent();
var group = new TransformGroup();
group.Children.Add(new TranslateTransform());
image.RenderTransform = group;
image.MouseLeftButtonDown += image_MouseLeftButtonDown;
image.MouseMove += image_MouseMove;
image.MouseLeftButtonUp += image_MouseLeftButtonUp;
}
private void image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
image.ReleaseMouseCapture();
}
private void image_MouseMove(object sender, MouseEventArgs e)
{
if (!image.IsMouseCaptured)
return;
var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).
Children.First(tr => tr is TranslateTransform);
var vector = start - e.GetPosition(border);
tt.X = origin.X - vector.X;
tt.Y = origin.Y - vector.Y;
}
private void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
image.CaptureMouse();
var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).
Children.First(tr => tr is TranslateTransform);
start = e.GetPosition(border);
origin = new Point(tt.X, tt.Y);
}
}
}
答案 0 :(得分:3)
以下代码为您提供相对于Border控件的坐标中已转换的Image控件的边界。您可以轻松检查边界是否位于Border控件内。
var rect = new Rect(image.RenderSize);
var bounds = image.TransformToAncestor(border).TransformBounds(rect);