UIWebView显示本地图片的方法

在UIWebView显示本地图片,由此可借助UIWebView实现图文混排(内容编码成html格式即可)。


//  ViewController.m
//
//  Created by zc on 8/1/14.
//  Copyright (c) 2014 cuibo. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
<UIWebViewDelegate>

@property(weak, nonatomic)IBOutlet UIWebView *contentWebView;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)button:(id)sender
{
    //编码图片
    UIImage *selectedImage = [UIImage imageNamed:@"1.jpg"];
    NSString *stringImage = [self htmlForJPGImage:selectedImage];
    
    //构造内容
    NSString *contentImg = [NSString stringWithFormat:@"%@", stringImage];
    NSString *content =[NSString stringWithFormat:
                        @"<html>"
                        "<style type=\"text/css\">"
                        "<!--"
                        "body{font-size:40pt;line-height:60pt;}"
                        "-->"
                        "</style>"
                        "<body>"
                        "%@"
                        "</body>"
                        "</html>"
                        , contentImg];

    //让self.contentWebView加载content
    [self.contentWebView loadHTMLString:content baseURL:nil];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //状态栏不显示网络状态,因为当前内容不是由网络下载的
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

//编码图片
- (NSString *)htmlForJPGImage:(UIImage *)image
{
    NSData *imageData = UIImageJPEGRepresentation(image,1.0);
    NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64Encoding]];
    return [NSString stringWithFormat:@"<img src = \"%@\" />", imageSource];
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。