我在 Xamarin 中有一個簡單的 WebView。我在 Windows 上使用 VisualStudio 2022。我下載了一張圖片。影像是存在的。我可以將它加載到 ImageView 中。我想用其他 html 代碼在 WebView 中顯示影像。
一個簡單的測驗代碼:
private async void WebViewImagetest()
{
string imageName = "Android-main2.jpg";
string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "media", imageName);
FileInfo file = new FileInfo(filePath);
image1.Source = filePath;
if (file.Exists)
{
var htmlSource = new HtmlWebViewSource();
htmlSource.Html = $"<html><body>"
$"<h1>Xamarin.Forms</h1>"
$"<p>Welcome to WebView.</p>"
$"<body style=\"width:100%\">"
$"<img src=\"https://cdn-images-1.medium.com/fit/t/1600/480/1*xh4Z2pj_oCDbT7Y5CQ0geQ.jpeg\"/><br>" //works
$"<img src=\"{filePath}\"/>" // not working
$"</body></html>";
Browser.Source = htmlSource;
}
else
{
await tester.ImageDownload("https://www.technokrata.hu/uploads/2021/08/Android-main.jpg", filePath);
Browser.Source = "https://google.com";
}
}
謝謝
uj5u.com熱心網友回復:
您可以使用HtmlWebViewSource設定源代碼,以便它可以在代碼隱藏中加載 html:
public EvaluateJavaScriptPage()
{
InitializeComponent();
_webView.Source = LoadHTMLFileFromResource();
}
HtmlWebViewSource LoadHTMLFileFromResource()
{
var source = new HtmlWebViewSource();
// Load the HTML file embedded as a resource in the .NET Standard library
var assembly = typeof(EvaluateJavaScriptPage).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream("WebViewSample.index.html");
using (var reader = new StreamReader(stream))
{
source.Html = reader.ReadToEnd();
}
return source;
}
uj5u.com熱心網友回復:
我有一個解決方案。我有兩個問題:
- 我必須用 js、css 和影像保存一個完整的網站
- 我有兩個 Xaml 頁面:一個用于保存網站(這是一個 API 頁面),一個用于顯示保存網站
首先,我保存 HTML 代碼。在此之后,我可以將保存的 HTML 加載到帶有HtmlWebViewSource. 當頁面加載時,WebView 保存快取(帶有 js、css 和影像)。在此之后,我可以關閉互聯網并在 WebView 或其他 WebView 中加載 HTML(帶有 js、csss 和影像)(因為共享網路快取)
這里是測驗代碼(我用這一行呼叫代碼WebCacheTest("https://pluszegy.com/kezolap/", htmlPath);:
private void WebCacheTest(string url, string path)
{
if (!File.Exists(path))
SaveWebsite(url, path);
else
LoadOfflineWebsite(path);
}
async void SaveWebsite(string url, string path)
{
string html = await tester.HtmlTartalomLet?ltése(url);
using (StreamWriter sr = File.CreateText(path))
{
sr.WriteLine(html);
var htmlSource = new HtmlWebViewSource();
htmlSource.Html = html;
Browser.Source = htmlSource;
}
}
void LoadOfflineWebsite(string path)
{
using (StreamReader sr = File.OpenText(path))
{
string html = sr.ReadToEnd();
var htmlSource = new HtmlWebViewSource();
htmlSource.Html = html;
Browser.Source = htmlSource;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/446867.html
