gpt4 book ai didi

WPF 图像平移约束

转载 作者:行者123 更新时间:2023-12-04 04:59:35 27 4
gpt4 key购买 nike

我试图弄清楚如何约束平移,以使图像完全保持在其包含边框的范围内。在这方面的任何帮助将不胜感激。谢谢....

<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);
}
}
}

最佳答案

以下代码以相对于 Border 控件的坐标为您提供转换后的 Image 控件的边界。您可以轻松检查边界是否位于 Border 控件内。

var rect = new Rect(image.RenderSize);
var bounds = image.TransformToAncestor(border).TransformBounds(rect);

关于WPF 图像平移约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16303726/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com