【问题标题】:How to resize image in UIWebview?如何在 UIWebview 中调整图像大小?
【发布时间】:2012-07-06 12:50:50
【问题描述】:

我在 UIWebview 中加载了一个 html 文件。我正在尝试在 UIWebview 中调整图像的大小并完成加载。在这个 webview 中,根据设备大小将 html 内容拆分为页数(下面的代码显示)。对于分页,我使用了滑动手势。在此之前它可以正常工作。在这个 html 文件中,我几乎没有大小不同的图像。有些图像超过了设备宽度。我需要修复图像的宽度,使其适合屏幕。我不想滚动 webview,因为我使用滑动手势进行分页。那么如何根据设备宽度重新调整图像的大小。

我使用以下代码

- (void)webViewDidFinishLoad:(UIWebView *)webView
{


     NSString *varMySheet = @"var mySheet = document.styleSheets[0];";

     NSString *addCSSRule =  @"function addCSSRule(selector, newRule) {"
     "if (mySheet.addRule) {"
     "mySheet.addRule(selector, newRule);"                              // For Internet Explorer
     "} else {"
     "ruleIndex = mySheet.cssRules.length;"
     "mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex);"   // For Firefox, Chrome, etc.
     "}"
     "}";

     NSString *insertRule1 = [NSString stringWithFormat:@"addCSSRule('html', 'padding: 0px; height: %fpx; -webkit-column-gap: 0px; -webkit-column-width: %fpx;')", webview4epub.frame.size.height, webview4epub.frame.size.width];
     NSString *insertRule2 = [NSString stringWithFormat:@"addCSSRule('p', 'text-align: justify;')"];

     [webview4epub stringByEvaluatingJavaScriptFromString:varMySheet];
     [webview4epub stringByEvaluatingJavaScriptFromString:addCSSRule];
     [webview4epub stringByEvaluatingJavaScriptFromString:insertRule1];
     [webview4epub stringByEvaluatingJavaScriptFromString:insertRule2];
     NSString* foundHits = [webview4epub stringByEvaluatingJavaScriptFromString:@"results"];
     NSMutableArray* objects = [[NSMutableArray alloc] init];

     NSArray* stringObjects = [foundHits componentsSeparatedByString:@";"];
     for(int i=0; i<[stringObjects count]; i++){
         NSArray* strObj = [[stringObjects objectAtIndex:i] componentsSeparatedByString:@","];
         if([strObj count]==3){
             [objects addObject:strObj];   
            }
        }


    int totalWidth = [[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollWidth"] intValue];

}

【问题讨论】:

    标签: objective-c ios xcode uiwebview


    【解决方案1】:

    这会将第一张图片的大小调整为 webViews 高度的 90%:

     NSString *imgHeightJSString = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('img')[0].style.maxHeight = '%fpx'", webView.bounds.size.height*0.90];
    [webView stringByEvaluatingJavaScriptFromString:imgHeightJSString];
    

    无论 view.size 是什么,这都是 90% 的 imageSize:

     [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('img')[0].style.maxHeight = '90%%'"] ;
    

    要设置宽度,只需使用 maxWidth 而不是 maxHeight。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-24
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      • 2015-09-27
      相关资源
      最近更新 更多