我正在开发一个图像查看器控件,其中包含一个位于滚动视图内的图像。
为了缩放,我在图像的布局变换中使用比例转换。
缩小是通过鼠标点击来实现的。如果用户点击图像,我希望鼠标位置处的像素位于滚动视图的可视区域中心。
为了实现这一点,我想要修改滚动视图偏移量,但我不确定如何计算正确的偏移量,以将像素放置在鼠标指针下方的中心位置。
这里有一个保持滚动条相对位置的描述。虽然可以正常工作,但并不是我想要的。
你如何正确计算偏移量呢?
以下是我的一些代码:
XAML 代码:
<ScrollViewer Margin="5" Name="scrvImagePanel" VerticalAlignment="Stretch"
CanContentScroll="True"
DockPanel.Dock="Left"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch"
HorizontalScrollBarVisibility="Auto"
VerticalContentAlignment="Stretch"
VerticalScrollBarVisibility="Auto"
Background="{StaticResource {x:Static SystemColors.ControlDarkBrushKey}}"
ScrollChanged="OnScrollChanged">
<Image Name="imgPicture"
MouseUp="imgMouseUp"
Stretch="None"
HorizontalAlignment="Left"
VerticalAlignment="Top"
>
<Image.LayoutTransform>
<TransformGroup>
<ScaleTransform x:Name="imgZoomTransform" ScaleX="1" ScaleY="1"></ScaleTransform>
</TransformGroup>
</Image.LayoutTransform>
</Image>
</ScrollViewer>
以及代码:
private void imgMouseUp(object sender, MouseButtonEventArgs e)
{
Point absScreenPos = e.GetPosition(imgPicture);
//calculate the new zoom factor
this.ZoomFactor = imgZoomTransform.ScaleX;
if (e.ChangedButton == MouseButton.Right)
{
this.ZoomFactor /= 2.0;
}
else if (e.ChangedButton == MouseButton.Left)
{
this.ZoomFactor *= 2.0;
}
//perform the zooming
this.DoZoom(this.ZoomFactor, absScreenPos.X, absScreenPos.Y);
}
private void DoZoom(double zoom, double posX, double posY)
{
// update the scale transform
imgZoomTransform.ScaleX = zoom;
imgZoomTransform.ScaleY = zoom;
this.AdjustScroll(new Point(posX, posY));
}
private void AdjustScroll(Point? centerPoint)
{
if(centerPoint != null)
{
var sv = this.scrvImagePanel;
double offsetX = (centerPoint.Value.X / this.imgPicture.ActualWidth) * sv.ActualWidth;
double offsetY = (centerPoint.Value.Y / this.imgPicture.ActualHeight) * sv.ActualHeight;
sv.ScrollToHorizontalOffset(offsetX);
sv.ScrollToVerticalOffset(offsetY);
}
}