关于Android如何把文字处理为图片

在Android内部有一套自己图片处理的机制,类似android.graphics.Canvas等等,使用它足以完成标题中的任务。

 

首先,我们要先生成一个Bitmap文件,以此作为画布:

Bitmap pic = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888);

这里使用了Bitmap的静态方法createBitmap。

createBitmap(int width, int height, Bitmap.Config config):Returns a mutable bitmap with the specified width and height.

前两个参数是宽,高,最后一个是图像每一个像素的存储类型,这里里使用了ARGB_8888,每个像素占用四个字节。

 

获得Bitmap之后,那么需要一个Canvas,可以理解为,Bitmap是画布,Canvas是画笔。

Canvas canvas = new Canvas(pic);

 

接下来,就可以用过Canvas提供的各种属性对图片进行编写了,在 官网指南 有许多类似drawXXXX()的方法,这里不细说,有需要的可以自己看一下。

注意,本文不使用drawText()直接将文字写进Bitmap,该方法主要的问题是,不管你输入多少内容,它都只占一行。

要实现文本内容自动换行,需要用到类 StaticLayout 。

这是一个很陌生的类,官方的解释为:

StaticLayout is a Layout for text that will not be edited after it is laid out. Use DynamicLayout for text that may change.

This is used by widgets to control text layout. You should not need to use this class directly unless you are implementing your own widget or custom display object, or would be tempted to call Canvas.drawText() directly.

看完仍然很陌生,不过它的继承是这样的:

java.lang.Object
   ↳ android.text.Layout
     ↳ android.text.StaticLayout

因此可以推断出这个类是一个用于处理Text的Layout。

该类的构造方法是:

StaticLayout(CharSequence source, TextPaint paint, int width, Layout.Alignment align, float spacingmult, float spacingadd, boolean includepad);

source:文本内容。

Paint:TextPaint继承字Paint,Paint是一个自定义画笔的,你可以通过他配置文本颜色,大小等等。

width:换行就是通过这个实现的,要定义宽度。

align:对齐方式。

spacingmult:行距。

spacingadd:字距。

includepad:不知干嘛的。。。

StaticLayout有一个很重要的方法,即:

 draw(Canvas c) :Draw this Layout on the specified Canvas.

通过它可以将生成的自动换行了的文本通过Canvas写进Bitmap。

 

自此,你已经可以将文字转成文字写进Bitmap,再通过Bitmap的compress方法生成图片文件。

compress(Bitmap.CompressFormat format, int quality, OutputStream stream):Write a compressed version of the bitmap to the specified outputstream.

 

posted @ 2014-04-25 13:50  yutoulck  阅读(547)  评论(0编辑  收藏  举报