Android: Best Way to Programmatically Make an Image and Save it to a Bitmap?

断了今生、忘了曾经 提交于 2020-01-06 05:34:08

问题


I have an app that connects to an external printer device and I need to take some user data and dynamically make an image and print it. The printer API requires a bitmap as input for printing. Note that I never want to draw the programmatically created image to the screen; the generation and printing of the image have no visible UI, it happens in the background.

So far I've considered doing it one of the following ways:

1) Make a canvas, never call the draw functions, translate it to a bitmap then print (a bit of a departure from the intended way to use the Canvas API)

2) Make a hidden ImageView xml layout, never make it visible, translate it to a bitmap then print (this can get tricky because I'd probably have to include it in the Activity's layout somewhere to dynamically edit it, but that consumes resources and feels inefficient)

What are your opinions on the best approach? Either of the two ways I've considered feel a bit hacky and leave me lusting for a dedicated API for custom image generation.


回答1:


The most platform-conformant solution is to take the Canvas approach.

First you should create a Bitmap of the needed dimensions and pass it to the Canvas(Bitmap) constructor. Then you draw whatever you need onto your canvas and retain the reference to the bitmap to use wherever you need throughout your app (in my case it's being sent to the printer).

From the Android Docs: For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View.

Example code:

bitmap = Bitmap.createBitmap(LABEL_SIDE_LENGTH, LABEL_SIDE_LENGTH, Bitmap.Config.ARGB_8888)

Next [in override fun draw(canvas: Canvas)] set the Canvas' Bitmap like so;

canvas.setBitmap(bitmap).

You retain the reference to bitmap and it can be used wherever you need



来源:https://stackoverflow.com/questions/58966338/android-best-way-to-programmatically-make-an-image-and-save-it-to-a-bitmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!