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];
}

@end


你可能感兴趣的:(图片,UIWebView,base64)