Android:以编程方式制作图像并将其保存到位图的最佳方法? [英] Android: Best Way to Programmatically Make an Image and Save it to a Bitmap?

查看:96
本文介绍了Android:以编程方式制作图像并将其保存到位图的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连接到外部打印机设备的应用程序,我需要获取一些用户数据并动态制作图像并进行打印.打印机API需要位图作为打印输入.请注意,我从不希望将以编程方式创建的图像绘制到屏幕上.图像的生成和打印没有可见的UI,它发生在后台.

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)制作画布,从不调用绘图函数,将其转换为位图然后打印(与使用Canvas API的预期方式有些出入)

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)创建一个隐藏的ImageView xml布局,从不使其可见,将其转换为位图然后打印(这可能会很棘手,因为我可能必须将其包含在Activity的布局中才能进行动态编辑,但是消耗资源,感觉效率低下)

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)

您对最佳方法有何看法?我考虑过的两种方法中的任一种都会让人感到有些不舒服,并让我渴望使用专门的API来自定义图像生成.

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.

推荐答案

最符合平台要求的解决方案是采用Canvas方法.

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

首先,您应该创建所需尺寸的位图,并将其传递给Canvas(Bitmap)构造函数.然后,您可以在画布上绘制所需的任何内容,并保留对位图的引用,以在整个应用程序中所需的任何地方使用(在我的情况下,该位图将被发送到打印机).

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).

Android文档中: 对于View层次结构或单个View的一小部分的软件渲染快照,建议从位图或图片创建Canvas并在View上调用draw(android.graphics.Canvas).

示例代码:

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

下一步[在override fun draw(canvas: Canvas)]中像这样设置Canvas的位图;

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

canvas.setBitmap(bitmap).

您保留对bitmap的引用,并且可以在任何需要的地方使用

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

这篇关于Android:以编程方式制作图像并将其保存到位图的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆