简体   繁体   English

iOS:缩放适合或在UIWebView中填充本地图像?

[英]iOS: scale fit or fill a local image in a UIWebView?

I'm using a UIWebView to display a gif animation stored on local disk, since UIImageView doesn't work with gif format. 我正在使用UIWebView来显示存储在本地磁盘上的gif动画,因为UIImageView不适用于gif格式。 Here is how I did it: 这是我的做法:

[webView loadData:imageData MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];

I found the solution from here . 我从这里找到了解决方案。

The problem now is the position of the image. 现在的问题是图像的位置。 See the screen capture below. 请参见下面的屏幕截图。 The UIWebView frame is (20, 20, 280, 280). UIWebView框架为(20、20、280、280)。 But the image is on the top left with its content size. 但是图像位于其内容大小的左上方。

How do I make this image scale to fit the UIWebView frame? 如何使图像缩放以适合UIWebView框架? I've tried "scalesPageToFit = YES" and "contentMode = UIViewContentModeScaleAspectFit", not working. 我已经尝试过“ scalesPageToFit = YES”和“ contentMode = UIViewContentModeScaleAspectFit”,但无法正常工作。 Maybe specifying something in html? 也许在html中指定一些内容? Please help. 请帮忙。

在此处输入图片说明

Actually, there are a few ways to use a animated GIF in imageview, and I think it's a lot better than use a webView just for this purpose. 实际上,有几种方法可以在imageview中使用动画GIF,我认为比为此目的使用webView更好。

I personnaly used SDWebImage, that can be easily used with cocoa pods. 我个人使用过SDWebImage,可以很容易地与可可豆荚一起使用。 See this: https://github.com/rs/SDWebImage 看到这个: https : //github.com/rs/SDWebImage

After integreted SDWebImage to your project, just import this header: 将SDWebImage集成到您的项目后,只需导入以下标头:

#import "UIImage+GIF.h"

And set the gif image like this: 并设置gif图片,如下所示:

self.imageView.image = [UIImage sd_animatedGIFNamed:@"loading"] //loading.gif it's a gif image inside the project bundle

If you still insist to use a webview, the only way to resize a image inside it, it's with javascript. 如果您仍然坚持使用网络视图,那么调整其中的图像大小的唯一方法就是使用javascript。

Select the image with javascript and edit it's height and width properties. 使用javascript选择图像并编辑其height和width属性。 You can run javascript code in a webView with the function below: 您可以使用以下功能在webView中运行javascript代码:

 [self.webView stringByEvaluatingJavaScriptFromString:@"-javascript code here-"];

So, in your case, it will be something like this: 因此,在您的情况下,将是这样的:

[self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('img')[0].style.width = '280px'"];

[self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('img')[0].style.height = '280px'"];

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

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