如何在UIWebview中调整图像大小?

时间:2012-07-06 12:50:50

标签: objective-c ios xcode uiwebview

我在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];

}

1 个答案:

答案 0 :(得分:0)

这会将第一张图片调整为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%%'"] ;

设置widht只需使用maxWidth而不是maxHeight。