图片自适应,UIWebView中图片的自适应

作者:计算机知识

在UIWebView中,大家恐怕会碰着由于UIWebView呈现的图样太大,而引致图片左右滚动,影响体验性;自个儿想再也改动一下图纸的高低,但不知晓怎么改的情形。

临时我们供给用webView加载一些html网页来呈现有个别事情内容,可是临时网页里的图形总是不能够依照显示器尺寸举办展示,往往由于网页图片过大招致浏览效果极差。由此照旧给出适配好的开始和结果文件,要么只可以前端去管理了。
图片自适应,UIWebView中图片的自适应。因而记下管理方法,防止未来蒙受相像的难点立马去管理。

import "NewsDetailV.h"

@interface NewsDetailV()
<
UIWebViewDelegate
>


/** 整个crrollV*/
@property (nonatomic,strong) UIScrollView *scroolV;
/**  名称label*/
@property (nonatomic,strong) UILabel *nameLabel;
/** 来源于*/
@property (nonatomic,strong) UILabel *originateLabel;
/** 时间*/
@property (nonatomic,strong) UILabel *timeLabel;
/** WebV*/
@property (nonatomic,strong) UIWebView *webView;
/** webv 的 H*/
@property (nonatomic,assign) CGFloat webH;
/** 加载视图*/
@property (nonatomic,strong) UIActivityIndicatorView *indicator;
/** 线*/
@property (nonatomic,strong) UIView *lineV;


@end
@implementation NewsDetailV

-(instancetype)initWithFrame:(CGRect)frame{

    if (self = [super initWithFrame:frame]) {
        [self initUserinterface];
    }
    return self;
}
#pragma mark -- UIWebViewDelegate


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

    NSString *height_str= [webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"];
    int height = [height_str floatValue];
    height  = 10;
    self.webH = height;
    [self.indicator stopAnimating];
    [self layoutSubviews];

}
-- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{

    [self.indicator stopAnimating];
    [MBProgressHUD showSuccess:@"详情加载失败..." toView:nil];
    self.webView.hidden = YES;
    CGFloat wholeH = (JobDetailVTitleVH   HeightOfLabel(TextFont(14, six))    HeightScreen(20, six));
    [[NSNotificationCenter defaultCenter]postNotificationName:JobDesriptionChangeHNoti object:@{@"h":@(wholeH)}];
    return;

}


#pragma mark -- 界面
-(void)initUserinterface{

    // 整个crrollV
    UIScrollView *scroolV = [[UIScrollView alloc]init];
    scroolV.backgroundColor = WhiteColor;
    [self addSubview:scroolV];
    self.scroolV = scroolV;

    // 名称label
    UILabel *nameLabel = MakeLabelWith(ImTextColor, Px36FontSize);
    nameLabel.numberOfLines = 0;
    [scroolV addSubview:nameLabel];
    self.nameLabel = nameLabel;

    // 来源于
    UILabel *originateLabel = MakeLabelWith(TextColor, Px24FontSize);
    originateLabel.numberOfLines = 0;
    [scroolV addSubview:originateLabel];
    self.originateLabel = originateLabel;

    // 时间
    UILabel *timeLabel = MakeLabelWith(LiTextColor, Px24FontSize);
    [scroolV addSubview:timeLabel];
    self.timeLabel = timeLabel;

    // 线
    UIView *lineV = MakeLineView(self.scroolV, LineColor);
    self.lineV = lineV;

    // WebV
    UIWebView *webView = [[UIWebView alloc]init];
    webView.backgroundColor = [UIColor clearColor];
    webView.scrollView.bounces = NO;
    webView.delegate = self;
    webView.scrollView.showsHorizontalScrollIndicator = NO;
    webView.scrollView.showsVerticalScrollIndicator = NO;
    webView.scrollView.scrollEnabled = NO;
    webView.dataDetectorTypes = UIDataDetectorTypeNone;
    webView.opaque = NO;
    webView.backgroundColor = [UIColor clearColor];
    [self.scroolV addSubview:webView];
    self.webView = webView;



}
#pragma mark -- 布局
-(void)layoutSubviews{

    [super layoutSubviews];
    // 整个crrollV
    self.scroolV.frame = CGRM(0, HomeMargin, S_W, self.height - HomeMargin);
    // 名称label
    [self.nameLabel sizeToFit];
    CGFloat nameLabelY = ( HeightMacroScreen(30));
    self.nameLabel.frame = CGRM(MainLeftMargin,nameLabelY, S_W - MainLeftMargin * 2, self.nameLabel.height);
    // 来源于
    CGFloat originateLabelY = (nameLabelY   self.nameLabel.height   HeightMacroScreen(42));
    // 时间
    [self.timeLabel sizeToFit];
    self.timeLabel.frame = CGRM(S_W - MainLeftMargin - self.timeLabel.width, originateLabelY, self.timeLabel.width, self.timeLabel.height);
    // 来源于
    [self.originateLabel sizeToFit];
    self.originateLabel.frame = CGRM(MainLeftMargin, originateLabelY, self.timeLabel.x - WidMacroScreen(10) - MainLeftMargin, self.originateLabel.height);
    // 线
    CGFloat lineVY;
    if (self.originateLabel.text != nil && self.originateLabel.text.length > 0) {
        lineVY = CGRectGetMaxY(self.originateLabel.frame)   HeightMacroScreen(30);
    }else{
        lineVY = CGRectGetMaxY(self.timeLabel.frame)   HeightMacroScreen(30);
    }
    self.lineV.frame = CGRM(MainLeftMargin, lineVY, S_W - MainLeftMargin * 2, HeightPtMacroScreen(1));

    // 职位描述WebV
    CGFloat webViewY =  CGRectGetMaxY(self.lineV.frame)   HeightMacroScreen(50);
    self.webView.frame = CGRM(MainLeftMargin / 2,webViewY, S_W - MainLeftMargin ,self.webH);

    self.scroolV.contentSize = CGSizeMake(S_W, CGRectGetMaxY(self.webView.frame));
}


#pragma mark -- setter
// 数据字典
-(void)setDic:(NSDictionary *)dic{

    _dic  = dic;
    NSDictionary *news = [dic getDictionaryForKey:@"news" defaultValue:nil];
    self.nameLabel.text = [news getStringValueForKey:@"title" defaultValue:nil];
    NSString *publisher = [news getStringValueForKey:@"publisher" defaultValue:nil];
    if (publisher != nil && publisher.length > 0) {
        self.originateLabel.text = [NSString stringWithFormat:@"【%@】",publisher];
    }
    NSString *create_time = [news getStringValueForKey:@"create_time" defaultValue:nil];
    if (create_time != nil && create_time.length >= 10) {
        self.timeLabel.text = [NSString stringWithFormat:@"%@.%@.%@",[create_time substringToIndex:4],[create_time substringWithRange:NSMakeRange(5, 2)],[create_time substringWithRange:NSMakeRange(8, 2)]];
    }

    NSString *content = [news getStringValueForKey:@"content" defaultValue:nil];
    NSString * WEB_STYLE ;
    /** 全局web样式 */
    if (IPHONE_5_S || IPHONE_4_S) {
        WEB_STYLE = @"<style>* {} img {max-width:250px;}img.alignleft {float:left;max-width:100px;margin:0 10px 5px 0;border:1px solid #ccc;background:#fff;padding:2px;}pre {font-size:9pt;line-height:12pt;font-family:Courier New,Arial;border:1px solid #ddd;border-left:5px solid #6CE26C;background:#f6f6f6;padding:5px;}a.tag {font-size:15px;text-decoration:none;background-color:#bbd6f3;border-bottom:2px solid #3E6D8E;border-right:2px solid #7F9FB6;color:#284a7b;margin:2px 2px 2px 0;padding:2px 4px;white-space:nowrap;}</style>";
    }else if (IPHONE_6_S){
        WEB_STYLE = @"<style>*{} img {max-width:310px;}img.alignleft {float:left;max-width:120px;margin:0 10px 5px 0;border:1px solid #ccc;background:#fff;padding:2px;}pre {font-size:9pt;line-height:12pt;font-family:Courier New,Arial;border:1px solid #ddd;border-left:5px solid #6CE26C;background:#f6f6f6;padding:5px;}a.tag {font-size:15px;text-decoration:none;background-color:#bbd6f3;border-bottom:2px solid #3E6D8E;border-right:2px solid #7F9FB6;color:#284a7b;margin:2px 2px 2px 0;padding:2px 4px;white-space:nowrap;}</style>";
    }else{
        WEB_STYLE = @"<style>*{} img {max-width:310px;}img.alignleft {float:left;max-width:120px;margin:0 10px 5px 0;border:1px solid #ccc;background:#fff;padding:2px;}pre {font-size:9pt;line-height:12pt;font-family:Courier New,Arial;border:1px solid #ddd;border-left:5px solid #6CE26C;background:#f6f6f6;padding:5px;}a.tag {font-size:15px;text-decoration:none;background-color:#bbd6f3;border-bottom:2px solid #3E6D8E;border-right:2px solid #7F9FB6;color:#284a7b;margin:2px 2px 2px 0;padding:2px 4px;white-space:nowrap;}</style>";
    }

    NSString * resultHtml = [NSString stringWithFormat:@"%@%@",WEB_STYLE ,content];
    // 过滤掉 img标签的width,height属性
    NSString *replaceWidth = @"(<img[^>]*?)\s width\s*=\s*\S ";
    NSString *replaceHeight = @"(<img[^>]*?)\s height\s*=\s*\S ";

    NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:

                                              replaceWidth options:0 error:nil];
    NSRegularExpression *regularExpression2 = [NSRegularExpression regularExpressionWithPattern:

                                               replaceHeight options:0 error:nil];
    resultHtml  = [regularExpression stringByReplacingMatchesInString:resultHtml options:0 range:NSMakeRange(0, resultHtml.length) withTemplate:@"$1"];
    resultHtml  = [regularExpression2 stringByReplacingMatchesInString:resultHtml options:0 range:NSMakeRange(0, resultHtml.length) withTemplate:@"$1"];
    [self.webView loadHTMLString:resultHtml baseURL:nil];



    [self layoutSubviews];
}


#pragma mark -- getter

-(UIActivityIndicatorView *)indicator{

    if (!_indicator) {
        _indicator =  [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        //3.1 位置
        _indicator.center = CGPointMake(S_W / 2, S_H / 2);
        //3.2 关闭隐藏
        _indicator.hidesWhenStopped = YES;
        [_indicator startAnimating ];
    }
    return _indicator;

}


@end

图片 1并没有适应的图形

预备贰个html文件,带有图片(图片尺寸明显高于手提式有线电话机显示屏卡塔尔(قطر‎,html文件代码如下:

寸草不留办法一:将scalesPageToFit属性设置为YES暗许意况下UIWebView加载HTML页面后,会以页面包车型大巴原来大小举办展示,亦即只要页面包车型大巴轻重超过UIWebView视口大小,UIWebView会现身滚动作效果应,何况客商只好通过滚动页面来查看分裂区域的剧情,不可能接纳手指的虚构手势来推广或减弱页面。设置:

<html>
    <head></head>
    <meta charset='UTF-8'>
    <body>
        <h1>图片自适应 (萌)</h1>
        ![](http://upload-images.jianshu.io/upload_images/1350326-248f797db0ae9afe.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/1240)</img>
        <h2>图片自适应 (美女)</h2>
        ![](http://upload-images.jianshu.io/upload_images/1350326-d81850f7ef08c360.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/1240)</img>
        <h2>图片自适应 (初音)</h2>
        ![](http://upload-images.jianshu.io/upload_images/1350326-db46c3c791ff3a0d.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/1240)</img>
        <h2>图片自适应 (鼬神)</h2>
        ![](http://upload-images.jianshu.io/upload_images/1350326-52d4afc93d31140d.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/1240)</img>
        <h2>图片自适应 (卡殿)</h2>
        ![](http://upload-images.jianshu.io/upload_images/1350326-05e198ac280d1966.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/1240)</img>
        <h2>图片自适应 (美少女)</h2>
        ![](http://img1.imgtn.bdimg.com/it/u=44603310,796842853&fm=21&gp=0.jpg)</img>
        <h2>图片自适应 (穹妹)</h2>
        ![](http://upload-images.jianshu.io/upload_images/1350326-27ea1e5bb749a771.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/1240)</img>
        <h2>图片自适应 (O(∩_∩)O哈哈~)</h2>
        ![](http://upload-images.jianshu.io/upload_images/1350326-2ad73139148bc49e.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/1240)</img>
    </body>
</html>
 mywebView.scalesPageToFit = YES;

初始化webView,加载html文件:

图片 2修改后

    UIWebView * webView = [UIWebView new];
    webView.delegate = self;
    [self.view addSubview:webView];

    webView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(64, 0, 0, 0));

    NSString * path = [[NSBundle mainBundle] pathForResource:@"text.html" ofType:nil];
    NSURL * url = [NSURL URLWithString:path];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];

本文由bwin必赢发布,转载请注明来源

关键词: 日记本 必赢亚洲 自适应 图片 UIWebView