Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

在 Android 中實作 LaTeX 公式轉圖片的轉換器

編輯:關於 Android 開發

在 Android 中實作 LaTeX 公式轉圖片的轉換器

本文將講解如何透過 codecogs.com 與 Google 提供的 API 介面,把 LaTeX 數學表達式轉換成圖片顯示。整體思路如下:

(1)透過 EditText 取得使用者輸入的 LaTeX 表達式,並對表達式格式化,使其便於網路傳輸。

(2)將格式化後的字串,透過 HTTP 請求發送至 codecogs.com 或 Google。

(3)取得網站返回的資料流,將其轉為圖片,並顯示在 ImageView 上。

1、取得並格式化 LaTeX 表達式

首先,這個網站的運作方式是:在 https://latex.codecogs.com/gif.latex? 後面接上公式內容即可返回圖片。例如 https://latex.codecogs.com/gif.latex?\alpha 會顯示一個希臘字母。所以我們只要在其後拼接想轉換的公式即可。需要注意的是,網路 URL 中的空格有時會被自動轉為加號「+」,因此傳輸時需要把空格去掉,或將其轉為「%20」。

首先要在 AndroidManifest 中加入網路訪問權限:

<uses-permission android:name="android.permission.INTERNET"/>

按鈕單擊時執行的核心邏輯:

String PicUrlCogs = "https://latex.codecogs.com/gif.latex?";
Url = new URL(PicUrlCogs + editText.getText().toString().replace(" ", ""));
new MyDownloadTask().execute(); // 執行 Http 請求
while (!finishFlag) {}          // 等待數據接收完畢
imageView.setImageBitmap(pngBM); // 顯示圖片
finishFlag = false;              // 標識回位

2、發送 Http 請求

這裡採用非同步執行緒的方式發送請求。先取得上一步的 URL,建立 Http 連結,把返回的數據導入輸入流,最後解碼為圖片並顯示在 ImageView 中。

protected Void doInBackground(Void... params) {
    try {
        URL picUrl = Url;                 // 獲取 URL 地址
        HttpURLConnection conn = (HttpURLConnection) picUrl.openConnection();
        conn.connect();                   // 打開連接
        if (conn.getResponseCode() == 200) { // 連接成功,返回數據
            InputStream ins = conn.getInputStream();      // 導入數據流
            pngBM = BitmapFactory.decodeStream(picUrl.openStream()); // 解析數據流
            finishFlag = true;            // 數據傳輸完畢標識
            ins.close();                  // 關閉數據流
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

完整的 MyDownloadTask 類(定義在 MainActivity 內):

class MyDownloadTask extends AsyncTask<Void, Void, Void> {
    protected void onPreExecute() { /* display progress dialog. */ }

    protected Void doInBackground(Void... params) {
        try {
            URL picUrl = Url;
            HttpURLConnection conn = (HttpURLConnection) picUrl.openConnection();
            conn.connect();
            if (conn.getResponseCode() == 200) {
                InputStream ins = conn.getInputStream();
                pngBM = BitmapFactory.decodeStream(picUrl.openStream());
                finishFlag = true;
                ins.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(Void result) { /* dismiss progress dialog and update ui */ }
}

3、顯示圖片

在上一步建立好網路連接類後,於 Button 單擊事件內實例化它來接收數據,再將返回的數據顯示在 ImageView 上。

btnPreview.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        try {
            Url = new URL(PicUrlCogs + editText.getText().toString().replace(" ", ""));
            new MyDownloadTask().execute();
            while (!finishFlag) {}
            imageView.setImageBitmap(pngBM);
            finishFlag = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

這樣一來,輸入 LaTeX 公式後單擊 PREVIEW 按鈕,就會在 ImageView 上顯示對應的圖片。由於本文只討論如何進行轉換,並未對圖片做任何優化處理,因此顯示出來可能偏小。另外,若採用去空格轉 URL 的方式,盡量保證 LaTeX 表達式嚴格合法(例如所有單元都用 {} 括起來)。

以下是完整的 MainActivity 代碼:

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends Activity {
    private String PicUrlGoogle = "https://chart.apis.google.com/chart?cht=tx&chl=";
    private String PicUrlCogs = "https://latex.codecogs.com/gif.latex?";
    private Button btnPreview;
    private EditText editText;
    private ImageView imageView;
    private Bitmap pngBM;
    private URL Url;
    private boolean finishFlag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnPreview = (Button) findViewById(R.id.btnPreview);
        imageView = (ImageView) findViewById(R.id.imageView);
        editText = (EditText) findViewById(R.id.editText);
        btnPreview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Url = new URL(PicUrlCogs + editText.getText().toString().replace(" ", ""));
                    new MyDownloadTask().execute();
                    while (!finishFlag) {}
                    imageView.setImageBitmap(pngBM);
                    finishFlag = false;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    class MyDownloadTask extends AsyncTask<Void, Void, Void> {
        protected void onPreExecute() { /* display progress dialog. */ }

        protected Void doInBackground(Void... params) {
            try {
                URL picUrl = Url;
                HttpURLConnection conn = (HttpURLConnection) picUrl.openConnection();
                conn.connect();
                if (conn.getResponseCode() == 200) {
                    InputStream ins = conn.getInputStream();
                    pngBM = BitmapFactory.decodeStream(picUrl.openStream());
                    finishFlag = true;
                    ins.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(Void result) { /* dismiss progress dialog and update ui */ }
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved