WPF 如何实现简单放大镜
控件名:Magnifier
作 者:WPFDevelopersOrg - 驚鏵
原文链接[1]:https://github.com/WPFDevelopersOrg/WPFDevelopers
框架使用
.NET40
;Visual Studio 2019
;实现此功能需要用到
VisualBrush
,放大镜展现使用Canvas
->Ellipse
.可以使用
VisualBrush
创建放大效果。设置
Visual
获取或设置画笔的内容。设置
ViewboxUnits
Absolute
坐标系与边界框无关。设置
Viewbox
获取或设置TileBrush
图块中内容的位置和尺寸。
当鼠标移动获取当前坐标点修改
VisualBrush
的Viewbox
。鼠标移动修改
Ellipse
的Canvas.Left
与Canvas.Top
跟随鼠标。
1) xaml
代码如下:
<Grid><Image Source="0.png" Stretch="Fill"Name="image" MouseMove="image_MouseMove"MouseEnter="image_MouseEnter" MouseLeave="image_MouseLeave"/><Canvas IsHitTestVisible="False" Name="MagnifierPanel"><Ellipse Stroke="LightBlue" Name="MagnifierCircle" Height="200" Width="200"><Ellipse.Fill><VisualBrush x:Name="MagnifierBrush" Visual="{Binding ElementName=image}" ViewboxUnits="Absolute"/></Ellipse.Fill></Ellipse></Canvas></Grid>
2) xaml.cs
代码如下:
private void image_MouseMove(object sender, MouseEventArgs e){var center = e.GetPosition(image);var length = MagnifierCircle.ActualWidth * _factor;var radius = length / 2;var viewboxRect = = new Rect(center.X - radius, center.Y - radius, length, length);MagnifierBrush.Viewbox = viewboxRect;MagnifierCircle.SetValue(Canvas.LeftProperty, center.X - MagnifierCircle.ActualWidth / 2);MagnifierCircle.SetValue(Canvas.TopProperty, center.Y - MagnifierCircle.ActualHeight / 2);}private void image_MouseEnter(object sender, MouseEventArgs e){MagnifierCircle.Visibility = Visibility.Visible;}private void image_MouseLeave(object sender, MouseEventArgs e){MagnifierCircle.Visibility = Visibility.Hidden;}
参考资料
[1]
原文链接: https://github.com/WPFDevelopersOrg/WPFDevelopers