Skip to main content
 首页 » 编程设计

c#之WebBrowser 缩放时滚动到某个点

2024年01月11日35luoye11

我正在尝试放大 .Net WebBrowser 控件中加载的网页上的图片。 例如,(100,100) 处有一张 100% 缩放的图片。现在我想将缩放比例设置为 200%,并将图片放在 WebBrowser 控件的左上角。

它几乎可以工作。如果该点位于屏幕左侧,则它有效。但如果该点更靠屏幕右侧,则新计算的点不正确。 Y总是正确的。只有 X 给我带来了问题。

任何人都知道 ScrollTo 与当前缩放因子的关系。或者它是否也与其他变量有关?我怀疑问题也是与屏幕大小相关的网页适配。 (在缩放时,它会删除不包含任何信息的网页的左右边缘。之后它会放大内容)。我需要真正的缩放比例只影响内容,而不影响布局。缩放时没有回流。

public class MyBrowser : WebBrowser 
 
    private int _zoom = 100; 
    public int Zoom 
    { 
        set 
        { 
            _zoom = value; 
 
            //perform zoom 
            object pvaIn = _zoom; 
            try 
            { 
                this._axIWebBrowser2.ExecWB( 
                    OLECMDID.OLECMDID_OPTICAL_ZOOM, 
                    OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER, 
                    ref pvaIn,  
                    IntPtr.Zero); 
            } 
            catch (Exception) 
            { 
                throw; 
            } 
        } 
        get 
        { 
            return _zoom; 
        } 
    } 
 
    private Point GetCurrentScroll() 
    { 
        int scrollX = this.Document.GetElementsByTagName("HTML")[0].ScrollLeft; 
        int scrollY = this.Document.GetElementsByTagName("HTML")[0].ScrollTop; 
 
        return new Point(scrollX, scrollY); 
    } 
 
    public void ZoomOnPoint(int x, int y, int zoomFactor) 
    { 
        int currentZoom = this.Zoom; 
 
        Point currentScroll = GetCurrentScroll(); 
 
        //Set new values 
        this.Zoom = newZoom; 
        this.Document.Window.ScrollTo( 
            currentScroll.X + ((x * currentZoom) / zoomFactor), //X is sometimes correct, mostly on the rightside of the screen 
            currentScroll.Y + y);                               //Y is correct 
    } 
} 

请您参考如下方法:

在 WPF 中,我将 X 和 Y 值与 H 和 V 缩放比例相乘,它有效:)