我正在使用RenderTransform
操作增量事件来翻译图像。如果弹开,图像会离开屏幕。如何限制图像留在网格内?
提前致谢
您需要以不离开容器的方式处理增量事件。这是来自我早期的项目(_scatterViewItemTransform 是我的轻弹项目上的 CompositeTransform,它托管在容器内(一个 ItemsControl,其 ItemsPanel 设置为网格):
protected override void OnManipulationDelta(ManipulationDeltaRoutedEventArgs e)
{
// Manipulation delta does not take UI scaling into account
var scaleString = Windows.ApplicationModel.Resources.Core.ResourceManager.Current.DefaultContext.QualifierValues["scale"];
var scale = Double.Parse(scaleString) * 0.01;
var x = _translateOrigin.X + e.Cumulative.Translation.X / scale;
var y = _translateOrigin.Y + e.Cumulative.Translation.Y / scale;
if (e.IsInertial)
{
while (x < Container.Padding.Left ||
x > Container.ActualWidth - Container.Padding.Right)
{
if (x < Container.Padding.Left)
x = -x + 2 * Container.Padding.Left;
if (x > Container.ActualWidth - Container.Padding.Right)
x = 2 * (Container.ActualWidth - Container.Padding.Right) - x;
}
while (y < Container.Padding.Top ||
y > Container.ActualHeight - Container.Padding.Bottom)
{
if (y < Container.Padding.Top)
y = -y + 2 * Container.Padding.Top;
if (y > Container.ActualHeight - Container.Padding.Bottom)
y = 2 * (Container.ActualHeight - Container.Padding.Bottom) - y;
}
}
_scatterViewItemTransform.TranslateX = x;
_scatterViewItemTransform.TranslateY = y;
if (!e.IsInertial)
{
BringIntoBounds();
}
}
public void BringIntoBounds()
{
if (_scatterViewItemTransform.TranslateX < Container.Padding.Left)
{
_scatterViewItemTransform.TranslateX = Container.Padding.Left;
}
if (_scatterViewItemTransform.TranslateX > Container.ActualWidth - Container.Padding.Right)
{
_scatterViewItemTransform.TranslateX = Container.ActualWidth - Container.Padding.Right;
}
if (_scatterViewItemTransform.TranslateY < Container.Padding.Top)
{
_scatterViewItemTransform.TranslateY = Container.Padding.Top;
}
if (_scatterViewItemTransform.TranslateY > Container.ActualHeight - Container.Padding.Bottom)
{
_scatterViewItemTransform.TranslateY = Container.ActualHeight - Container.Padding.Bottom;
}
}