亲宝软件园·资讯

展开

基于WPF实现简单放大镜效果

驚鏵 人气:0

WPF 如何实现简单放大镜

框架使用.NET40

Visual Studio 2019;

实现此功能需要用到 VisualBrush ,放大镜展现使用 Canvas -> Ellipse .

实现代码

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

效果图

加载全部内容

相关教程
猜你喜欢
用户评论