程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 【uwp】淺談China Daily 中劃詞翻譯的實現,uwpdaily

【uwp】淺談China Daily 中劃詞翻譯的實現,uwpdaily

編輯:C#入門知識

【uwp】淺談China Daily 中劃詞翻譯的實現,uwpdaily


學習uwp開發也有一段時間了,最近上架了一個小應用(China Daily),現在准備將開發中所學到的一些東西拿出來跟大家分享交流一下。

先給出應用的下載鏈接:China Daily , 感興趣的童鞋可以看一看。

廢話就扯到這裡,接下來,我們來看看這個應用中的劃詞翻譯功能是如何實現的(也順帶談談點擊正文中的圖片顯示詳情)。

 

新聞的主體是放在一個WebView裡面的,所以,說白了就是解決WebView的問題(JS通知後台C#以及C#調用JS)。

1.XAML

<WebView x:Name="webView"
         NavigationCompleted="webView_NavigationCompleted"
         ScriptNotify="webView_ScriptNotify"
         />

2.添加對alert的監聽

private async void webView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
    //檢測alert
    var inject = WebViewUtil.RiseNotification();

    await webView.InvokeScriptAsync("eval", new List<string>() { inject });
}
public static string RiseNotification()
{
    string func = @"window.alert = function(arg) {
                        window.external.notify(arg);
                    };";
    return func;
}

3.監聽到alert時的處理

private void webView_ScriptNotify(object sender, NotifyEventArgs e)
{
    var data = e.Value.Trim();

    if (data.Contains("http://"))
    {
        // 判斷點擊的是圖片
        LoadImage(data);
    }
    else
    {
        // 判斷點擊的是文本
        LoadTranslation(data);
    }
}

此處的data是WebView通過JS方法傳遞過來的信息。如果點擊的是圖片,則傳遞圖片的url;如果點擊(選中)的是文本,則把文本傳遞過來。

當然,WebView會這麼機智的將我們想要的信息准確的傳遞過來嗎?答案是肯定的,前提是我們要告訴它應該怎麼做。

4.交給WebView的錦囊

4.1 明確任務

China Daily 接口沒有直接返回完整的html,但它將主要的內容都交到了我們手裡,而我們所需要完成的,就是把這些資源給組合起來,再交給WebView。

4.2 前期准備

public static int GetBaseFontSize() => DeviceUtils.IsMobile ? 32 : 14;

public static int GetBaseLineHeight() => DeviceUtils.IsMobile ? 64 : 28;

/// <summary>
/// 內容樣式
/// </summary>
/// <returns></returns>
public static string GetContentCSS()
{
    string commonStyle = "touch-action: pan-y; font-family:'微軟雅黑';" + (DeviceUtils.IsMobile ? "padding:2px 19px 2px 19px;" : "text-align:justify;  padding:2px 16px 2px 5px;");

    string colorstyle = "background-color:#ffffff; color:#000000;" ;

    string webStyle = "body{" + commonStyle + colorstyle +
                      $"font-size:{GetBaseFontSize()}px; line-height:{GetBaseLineHeight()}px" +
                      "}";
    string css = "<style>" + webStyle + "</style>";

    return css;
}
/// <summary>
/// JS方法
/// </summary>
/// <returns></returns>
public static string GetContentJS()
{
    string js = @"window.lastOriginData = '';
                  
                  function mouseUp (param) {
                      if(param == 'y') return;
                      if (window.getSelection) {
                          var str = window.getSelection().toString();
                          window.lastOriginData = str.trim();
                          alert(str);
                      }
                  };
                  function getImageUrl(url) {
                      alert(url);
                  }
                  window.onload = function () {
                      var as = document.getElementsByTagName('a');
                      for (var i = 0; i < as.length; i++) {
                          as[i].onclick = function (event) {
                              window.external.notify(JSON.stringify({ 'type': 'HyperLink', 'content': this.href }));
                              return false;
                          }
                      }
                  };";

    return js;
}

GetContentCSS方法只是用於給整段新聞添加一個樣式,使布局看起來美觀一點,大家不用太在意。

可以關注下的是GetContentJS方法。小小的說明一下,window.onload部分不用太在意;mouseUp部分用於在光標離開的時候,通知後台C#用戶所選中的文本;而getImageUrl方法則是用於傳遞所點擊的圖片的url。當然,接口給定的內容中一般來說不可能給出img的onclick事件,因此,這個部分也需要我們進行相關處理:

private const string imgStyle = "style='max-width: 100%' onclick='getImageUrl(this.src)'";
/// <summary>
/// 處理新聞內容(主要是過濾Style和為圖片添加點擊事件)
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public static string UpdateContentStyle(string content)
{
    if (string.IsNullOrEmpty(content))
        return null;

    // 正則匹配img,統一替換它的Style,並添加點擊事件(此處該如何匹配還應視具體情況而定)
    var matches = Regex.Matches(content, @"<img[\s\S]*?(style='[\s\S]*?')[\s\S]*?/?>");
    List<string> list = new List<string>();

    if (matches.Count > 0)
        list.Add(matches[0].Groups[1].Value);

    for (int i = 1; i < matches.Count - 1; i++)
    {
        if (!list.Contains(matches[i].Groups[1].Value))
            list.Add(matches[i].Groups[1].Value);
    }

    foreach (var item in list)
    {
        content = content.Replace(item, imgStyle);
    }

    return content;
}

4.3 整合資源

/// <summary>
/// 將新聞主體部分拼湊成一段完整的html
/// </summary>
/// <returns></returns>
public string ProcessNewsContent()
{
    var newsContent = WebViewUtil.UpdateContentStyle(news.Content);

    string webContent = "<html><head>" + contentCSS + "<script>" + js + "</script>" + "</head>" + "<body><div onmouseup='mouseUp()'> " + newsContent + "</div>" + "</body></html>";

    return webContent;
}

簡單說明一下,contentCSS就是上方GetContentCSS方法返回的結果,js是GetContentJS方法返回的結果,news則是用於展示的新聞,news.Content則是新聞內容,

它的大概模樣如下(截取部分):

<p>
    <strong>Today three top economists look at the state of the global economy and give their outlooks for 2017.</strong>
</p>
<p>
    <img attachmentid=""232694"" src=""http://iosnews.chinadaily.com.cn/newsdata/news/201612/26/432220/picture_232694.jpg"" style='max-width: 100%' />
</p>

4.4 交貨

webView.NavigateToString(content);

此處的content自然就是我們整合好的資源了(一段字符串)。

5.存在的問題

至此,關鍵的部分均已實現,讓我們按照以上套路運行一番。(假設LoadImage和LoadTranslation方法都只是將JS傳遞過來的信息直接顯示出來)

我們發現,PC上正常運行無壓力;而手機上卻是另一番光景——選中文本的時候沒有任何反應,取消選中的時候反倒是顯示信息了。(尚未搞清楚是為何)

因此,我采用了一個糾正措施,如下:

/// <summary>
/// 為wp修正文本選中問題
/// </summary>
public async void ProcessTextSelected4Phone(string text)
{
    if (DeviceUtils.IsMobile)//wp上表現和電腦上不一樣...
    {
        // 判斷是否選中文本
        DataPackage dataPackage = await webView.CaptureSelectedContentToDataPackageAsync();
        if (dataPackage == null)// 表示未選中文本
        {
            LoadTranslation(null);// 隱藏翻譯欄
            return;
        }

        var handleMouseUp = string.IsNullOrEmpty(text) ? false : true;
        await webView.InvokeScriptAsync("mouseUp", new[] { handleMouseUp ? "y" : "" });// 若參數為y,則不觸發事件
    }
}

其實質就是在手機端,在正常的mouseUp觸發基礎上,通過代碼主動多觸發一次mouseUp,以達到修正目的。

6.Demo

http://files.cnblogs.com/files/lary/Demo.rar

7.參考

【WP8.1】WebView筆記:http://www.cnblogs.com/bomo/p/4320077.html

 

初次寫博客,多多包涵

 

花開成景,花落成詩。不問花開幾許,只問淺笑安然。(●'◡'●)

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved