Swift iOS : 裝入webview時,如何讓圖片都顯示在螢幕內

RecoReco發表於2017-08-21

webview裝入的網頁,常常有幅面比較的圖,這些圖會超出手機的寬度,因此導致顯示不完整。

比如如下案例,加入了兩個圖片,大小分別為:

650x300
150x150複製程式碼

在iPhone SE的模擬器下,預設情況下,前一張圖會在寬度上超出,後一張可以顯示完整。

import UIKit
class Page: UIViewController{
    var c : UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        c = UIWebView()
        c.frame = super.view.frame
        view.addSubview(c)
        c.frame.origin.y += 20
        let html = "<img src=\"https://via.placeholder.com/650x300\"><img src=\"https://via.placeholder.com/150x150\">"
        let url = URL(string:"http://")
        c.loadHTMLString(html, baseURL: url)

    }
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window!.rootViewController = Page()
        self.window?.makeKeyAndVisible()
        return true
    }
}複製程式碼

想要更加優雅的適配圖片,可以使用css,強制要求顯示寬度為100%,從而縮放寬度到裝置寬度。做法就是加入一個html頭字串,加入到你自己裝入的html字串的頭部。如:

import UIKit
class Page: UIViewController{
    var c : UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        c = UIWebView()
        c.frame = super.view.frame
        view.addSubview(c)
        c.frame.origin.y += 20
        let html = htmlhead + "<img src=\"https://via.placeholder.com/650x300\"><img src=\"https://via.placeholder.com/150x150\">"
        let url = URL(string:"http://")
        c.loadHTMLString(html, baseURL: url)

    }
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window!.rootViewController = Page()
        self.window?.makeKeyAndVisible()
        return true
    }
}
let htmlhead =  "<!DOCTYPE html>" +
    "<html>" +
    "<head>" +
    "<meta charset=\"UTF-8\">" +
    "<style type=\"text/css\">" +
    "html{margin:0;padding:0;}" +
    "body {" +
    "margin: 0;" +
    "padding: 0;" +
    "}" +
    "img{" +
    "width: 90%;" +
    "height: auto;" +
    "display: block;" +
    "margin-left: auto;" +
    "margin-right: auto;" +
    "}" +
    "</style>" +
"</head>"複製程式碼

出來的效果,是兩張圖片全部充滿寬度,其中一個圖片縮小,不會產生鋸齒,一個圖片放大,有些鋸齒。對於大量照片的html文件,一般都是縮小的,因此看起來還是過得去的。

相關文章