Scale html content in Webview

2019-05-30 11:12发布

问题:

I load a local HTML template into a WebView. My webview's frame size is very small (250X300). I use this to show only a preview. The problem is, I can't see the entire html content in the webview. I can see only the top left. I have to scroll to see the entire content. So is there any possiblity to set the scale or zoom factor for the webview?

回答1:

If it is good enough for you to zoom text only, then use the methods -[WebView makeTextSmaller:] and -[WebView makeTextLarger:] and to reset the text size -[WebView makeTextStandardSize:] as documented for WebView. These methods correspond to "Cmd -" and "Cmd +" and "Cmd 0" in Safari.

If you want to scale the whole content of a WebView including images I use the following method:

- (void) zoomWebView:(WebView *)aWebView withFactor:(float)fac
{
    NSString *script = @"document.body.style.zoom";
    float oldFac = [[aWebView stringByEvaluatingJavaScriptFromString:script] floatValue];
    if( oldFac==0 ){ oldFac = 1.0; }
    NSString *res = [aWebView stringByEvaluatingJavaScriptFromString:
            [NSString stringWithFormat:@"%@='%1.2f';", script, (oldFac*fac)]];
    [aWebView setNeedsDisplay:YES];
}


回答2:

I got the answer after a little play around.

    [[[[[previewWeb mainFrame] frameView] documentView] superview] scaleUnitSquareToSize:NSMakeSize(.5, .5)];


回答3:

You can use the undocumented

- (void)_setZoomMultiplier:(float)m isTextOnly:(BOOL)isTextOnly

Note : That this may cause problems with submissions to the App Store.