当前位置:网站首页>Development based on cefsharp (6) browser web page scaling

Development based on cefsharp (6) browser web page scaling

2020-12-07 21:46:51 itread01

One 、 Web page scaling analysis

Zoom entry

1、Ctrl + Mouse wheel zoom

2、 Zoom sub menu zoom

3、 Search box page zoom button zoom

Zoom properties and commands

ChromiumWebBrowser Provides scaling values 、 Zoom level 、 Zoom in / Zoom out / Reset command, etc , Here's the picture

 

Two 、 Mouse wheel zoom

Simple zoom implementation

To achieve scaling , First, capture the mouse scrolling event , Initializing WebBrowser Add

 this.CefWebBrowser.PreviewMouseWheel += CefWebBrowser_PreviewMouseWheel;

And realize CefWebBrowser_PreviewMouseWheel Method , There is a need to judge Ctrl Whether to press , The code is as follows :

private void CefWebBrowser_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
    if ((Keyboard.Modifiers & ModifierKeys.Control) != ModifierKeys.Control) return;
    try
    {
        if (e.Delta > 0)
        {
            CefWebBrowser.ZoomInCommand.Execute(null);
        }
        else if (e.Delta < 0)
        {
            CefWebBrowser.ZoomOutCommand.Execute(null);
        }
        e.Handled = true;
    }
    catch (Exception ex)
    {

    }
}

among e.Delta Bigger than 0 Enlarge the web page when , Smaller than 0 When you zoom in

Page reset

General habits Ctrl+0 Reset page size , Therefore, it is necessary to CefWebBrowser_PreviewKeyDown Add combination key processing in , Be careful :0 Of key The value contains the keypad (NumPad0), The code is as follows :

if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control
               && (e.Key == Key.D0 || e.Key == Key.NumPad0))
{
    CefWebBrowser.ZoomResetCommand.Execute(null);
    // CefWebBrowser.SetZoomLevel(0);
}

ZoomResetCommand The zoom level can be restored to the zoom level when the page was opened ( The default is 100%, If there is a setting, it may not be 100%), Strong reset to 100% You can use comment code  CefWebBrowser.SetZoomLevel(0);

3、 ... and 、 Increase zoom level display

The content above can be zoomed in , But I don't know the specific scale ( Level ), Look at Edge Zoom display

When the page zooms, a zoom button is displayed in the search box , And show the zoom window below , Next, implement the following content

1、 Expansion Kit search box

  As the content of the search box will be more and more , So we can't use the universal MTextBox, You need to create a new search box to expand the package later , newly build CustomControl MSearchText,

And from MTextBox Move bricks to MSearchText

 

 MSearchText Control elements need to add dependency properties ZoomLevelType Used to determine whether the zoom button is displayed 、 Zoom out 、 Zoom in

You need a Menu Type , New enumeration type None Don't show zoom

public enum ZoomType
{
    None,
    In,
    Out,
}

Add dependency properties

public static readonly DependencyProperty ZoomLevelTypeProperty = DependencyProperty.Register("ZoomLevelType", typeof(ZoomType), typeof(MSearchText));
/// <summary>
/// ZoomLevelType  Zoom type 
/// </summary>
public ZoomType ZoomLevelType
{
    get => (ZoomType)GetValue(ZoomLevelTypeProperty);
    set => SetValue(ZoomLevelTypeProperty, value);
}

stay Xaml in Search Add a column to the box ZoomButon

 <Grid Grid.Column="2">
      <ToggleButton x:Name="PART_ZoomButton" FontSize="16" Style="{DynamicResource ToggleButton.FontButton}" Margin="2,0"/>
 </Grid>

Add display state control to trigger

<Trigger Property="ZoomLevelType" Value="None">
    <Setter TargetName="PART_ZoomButton" Property="Visibility" Value="Collapsed" />
</Trigger>
<Trigger Property="ZoomLevelType" Value="In">
    <Setter TargetName="PART_ZoomButton" Property="Content" Value="&#xe678;" />
</Trigger>
<Trigger Property="ZoomLevelType" Value="Out">
    <Setter TargetName="PART_ZoomButton" Property="Content" Value="&#xe620;" />
</Trigger>

2、ZoomLevelType Type tie

stay MSearchText  add Binding,ViewModel No more details here .

 <controls:MSearchText Grid.Column="1" Watermark=" Search for or type in Web Address " Text="{Binding CurrentUrl, UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"
                                      ZoomLevelType="{Binding ZoomLevelType}" KeyDown="Search_OnKeyDown"/>

When the page zooms , Execute SetSearchZoomStatus Method

private void SetSearchZoomStatus()
{
    if (CefWebBrowser.ZoomLevel < 0)
    {
        ViewModel.ZoomLevelType = ZoomType.Out;
    }
    else if (CefWebBrowser.ZoomLevel > 0)
    {
        ViewModel.ZoomLevelType = ZoomType.In;
    }
    else
    {
        ViewModel.ZoomLevelType = ZoomType.None;
    }
}

Execution effect :

3、 Zoom small window

Edge Zoom window has the following features :

1、 Scaling is updated in real time

2、 When you click zoom Button Pop up a small window

3、Ctrl+ Zoom in and out of the mouse wheel The small window disappears in a few seconds

First, design a small window , Adopt Popup, Continue to expand the suite MSearchText, increase Popup Pop up , increase TextBlock Used to display zoom , Three Button They are shrinking 、 Zoom in 、 Reset

<Popup x:Name="PART_ZoomPopUp" PopupAnimation="Fade" Placement="Bottom" PlacementTarget="{Binding ElementName=PART_ZoomButton}"
       StaysOpen="{TemplateBinding ZoomStaysOpen}" AllowsTransparency="True" HorizontalOffset="-180" VerticalOffset="5" IsOpen="{TemplateBinding ZoomIsChecked}">
    <Border Background="{DynamicResource WebBrowserBrushes.SearchZoomPopupBackground}" CornerRadius="5">
        <DockPanel Width="251" Height="40">
            <TextBlock Text="{TemplateBinding ZoomRatio}" VerticalAlignment="Center" Margin="15,0,0,0" HorizontalAlignment="Left"/>
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,0,15,0">
                <Button Content="&#xe60c;" Style="{DynamicResource Button.FontButton}" Width="26" Height="26"/>
                <Button Content="&#xe699;" Style="{DynamicResource Button.FontButton}" Margin="10,0,0,0" Width="26" Height="26"/>
                <Button Content=" Reset " Style="{DynamicResource Button.FontButton}" Margin="10,0,0,0" Width="64" Background="{DynamicResource WebBrowserBrushes.SearchZoomPopupResetBackground}"/>
            </StackPanel>
        </DockPanel>
    </Border>
</Popup>

 Popup Of PlacementTarget Point to the zoom button . The code for the zoom button is as follows :

<ToggleButton xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  x:Name="PART_ZoomButton" FontSize="16" 
Style="{DynamicResource ToggleButton.FontButton}" IsChecked="{TemplateBinding ZoomIsChecked}" Margin="2,0"/>

According to the characteristics 1, Need to add dependency properties ZoomRatio For real-time re alignment ratio ,

According to the characteristics 2 And features 3 The selected state of the zoom button needs to be controlled , So add dependency properties  ZoomIsChecked,

At the same time, we need to control Popup Whether or not the display remains displayed , So add dependency properties  ZoomStaysOpen,

stay ViewModel You also need to add the above attributes in ( Independent properties )

Then yes MSearchText The binding is as follows :

<controls:MSearchText Grid.Column="1" Watermark=" Search for or type in Web Address " Text="{Binding CurrentUrl, UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"
                      ZoomLevelType="{Binding ZoomLevelType}" ZoomRatio="{Binding ZoomRatio}" ZoomIsChecked="{Binding ZoomIsChecked}"
                      ZoomStaysOpen="{Binding ZoomStaysOpen}"  KeyDown="Search_OnKeyDown"/>

4、 Back end code control

Expansion Kit SetSearchZoomStatus Method , Increase the selected state and display ratio ( The display scale has been simplified , It's not exactly right ) The control of

private void SetSearchZoomStatus()
{
    if (CefWebBrowser.ZoomLevel < 0)
    {
        ViewModel.ZoomLevelType = ZoomType.Out;
        ViewModel.ZoomIsChecked = true;
        if (CefWebBrowser.ZoomLevel > -1)
        {
            ViewModel.ZoomRatio = "90%";
        }
        else if (CefWebBrowser.ZoomLevel <= 1)
        {
            var radio = Math.Round((CefWebBrowser.ZoomLevel + 5) / 5 * 100);
            ViewModel.ZoomRatio = $"{radio}%";
        }
    }
    else if (CefWebBrowser.ZoomLevel > 0)
    {
        ViewModel.ZoomLevelType = ZoomType.In;
        ViewModel.ZoomIsChecked = true;
        var radio = Math.Round((1 + CefWebBrowser.ZoomLevel) * 100, 2);
        ViewModel.ZoomRatio = $"{radio}%";
    }
    else
    {
        ViewModel.ZoomLevelType = ZoomType.None;
        ViewModel.ZoomIsChecked = false;
    }

}

Then add the timer , Start the timer when the mouse wheel zooms in , Used to judge Popup Whether it disappears ,

Here we use a variable _zoomWaitingCount Judge whether to hide , If you keep rolling and sliding _zoomWaitingCount Re count

private void CefWebBrowser_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
    if ((Keyboard.Modifiers & ModifierKeys.Control) != ModifierKeys.Control)
    {
        ViewModel.ZoomStaysOpen = false;
        return;
    }
    try
    {
        _zoomWaitingCount = 0;
        if (e.Delta > 0)
        {
            if (this.CefWebBrowser.ZoomLevel < 4)
            {
                CefWebBrowser.ZoomInCommand.Execute(null);
            }
            ViewModel.ZoomStaysOpen = true;
        }
        else if (e.Delta < 0)
        {
            if (this.CefWebBrowser.ZoomLevel > -4)
            {
                CefWebBrowser.ZoomOutCommand.Execute(null);
            }
            ViewModel.ZoomStaysOpen = true;
        }
        _zoomToolTimer.Elapsed -= ZoomToolTimer_Elapsed;
        _zoomToolTimer.Elapsed += ZoomToolTimer_Elapsed;
        _zoomToolTimer.AutoReset = true;
        _zoomToolTimer.Enabled = true;
        SetSearchZoomStatus();
        e.Handled = true;
    }
    catch (Exception ex)
    {

    }
}

private void ZoomToolTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    if (_zoomWaitingCount > 2)
    {
        _zoomToolTimer?.Stop();
        ViewModel.ZoomIsChecked = false;
        ViewModel.ZoomStaysOpen = false;
        _zoomWaitingCount = -1;
        return;
    }

    if (_zoomWaitingCount > -1)
    {
        _zoomWaitingCount++;
    }
}

  Execution effect :

 

Small pop-up button command binding, here will not repeat , Check the code for details

Four 、 Original code address

gitee Address :https://gitee.com/sirius_machao/mweb-bro

版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201207214620645f.html