我正在使用 React Native 和Native Modules为Smart POS构建一个应用程序以使用 Java 本机功能,我需要将一张票的图片发送到打印机,我收到 HTML 代码中的票布局并需要将其转换为一个图像,为此,我在 Web 视图中呈现此 HTML 代码,然后使用画布打印到位图
问题:图像未正确渲染,宽度和高度始终等于 0
我对原生开发没有太多经验,所以我的代码有问题吗?
我的代码:
@ReactMethod
public void print() {
Activity activity = getCurrentActivity();
Context context = reactContext.getApplicationContext();
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/print.jpg";
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
WebView wv = new WebView(context);
wv.loadData("<html><body style='width: 300px; height: 300px'><h1 style='color: #000'>Test</h1></body></html>", "text/html", null);
// mede o tamanho da webview
wv.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
// define o layout da webview
wv.layout(0, 0, wv.getMeasuredWidth(), wv.getMeasuredHeight());
// cria um bitmap
Bitmap bm = Bitmap.createBitmap(wv.getMeasuredWidth(), wv.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
// desenha o bitmap no canvas
Paint paint = new Paint();
Canvas cv = new Canvas(bm);
int height = bm.getHeight();
cv.drawBitmap(bm, 0, height, paint);
wv.draw(cv);
try {
FileOutputStream out = new FileOutputStream(path);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}