简体   繁体   English

如何仅在 UIWebView 中为 Image 设置合适的大小?

[英]How to make fit size only for Image in UIWebView?

I loaded HTML to my UIWebView that including both Text and Images .我将HTML加载到我的UIWebView ,其中包括TextImages

Text is fit to UIWebView and Images are not fit to UIWebView . Text适合UIWebViewImages不适合UIWebView

It's too large in UIWebView .它在UIWebView太大了。

It's showing scroll bar at the end of the UIWebView .它在UIWebView的末尾显示滚动条。

I want to adjust image fit size in UWebView.我想在 UWebView 中调整图像大小。 So i tested with following codes.所以我用以下代码进行了测试。

self.myWebView.scalesPageToFit = YES;

However it's fixed including Text and Text is too small to read and Images are fixed.但是它是固定的,包括文本和文本太小而无法阅读,并且图像是固定的。

I want to set Text Normally and only want to fit size Image in UIWeView .我想正常设置 Text 并且只想在UIWeView适合大小 Image 。

How can i do it?我该怎么做?

I have solve this problem using css.我已经使用 css 解决了这个问题。 The css contained within the style tags below will make sure to automatically resize your images maintaining aspect ratio for the width of the UIWebView.下面样式标签中包含的 css 将确保自动调整图像大小,保持 UIWebView 宽度的纵横比。 Hope this helps!希望这可以帮助!

NSString *strTemplateHTML = [NSString stringWithFormat:@"<html><head><style>img{max-width:100%%;height:auto !important;width:auto !important;};</style></head><body style='margin:0; padding:0;'>%@</body></html>", @"insert your html content here"];

[webView loadHTMLString:strTemplateHTML baseURL:nil];

Use the viewport meta tag is used by UIWebView on the iPhone/iPad to determine how to display a web page.使用 iPhone/iPad 上的 UIWebView 使用视口元标记来确定如何显示网页。

 <meta name="viewport" content="width=device-width, maximum-scale=1.0" />

refer below link for more details:请参阅以下链接了解更多详情:

https://developer.apple.com/library/ios/DOCUMENTATION/AppleApplications/Reference/SafariWebContent/UsingtheViewport/UsingtheViewport.html https://developer.apple.com/library/ios/DOCUMENTATION/AppleApplications/Reference/SafariWebContent/UsingtheViewport/UsingtheViewport.html

The following code snippet may help you以下代码片段可能对您有所帮助

NSString *fontString = @"<!DOCTYPE html><html>\
    <head>\
    <style>\
    img{";
        NSString *imageDimensionsStr = [NSString stringWithFormat:@"max-width: %fpx; max-height: %fpx;}",self.view.frame.size.width - 50.0f, self.view.frame.size.height/2];
        fontString =[fontString stringByAppendingString:imageDimensionsStr];
fontString = [fontString stringByAppendingString:@"</style></head><body>"];
    fontString = [[fontString stringByAppendingString:htmlString] stringByAppendingString:@"</body></html>"];
    [webView loadHTMLString:fontString baseURL:nil];

The above code will resize the width and height of the image according to view dimension.上面的代码将根据视图尺寸调整图像的宽度和高度。 You can change according to your requirement.您可以根据您的要求进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM