如何在Android中将文本转换为位图

时间:2014-02-24 05:47:05

标签: android bitmap android-canvas draw bitmapfactory

请帮我画一个圆角矩形作为背景的文字。我必须在画布上绘制许多文本,文本具有圆形背景。所以我正在尝试编写一个函数“createTextBitmap”,它返回一个位图图像,以便我们可以在主画布上绘制图像(由函数返回)。 'createTextBitmap'函数可以返回一个创建的位图,位图图像就是一个,它包含带有圆边背景的文本......

我试过了一个,下面给出了。

 private Bitmap ProcessingBitmap(String text,Paint paint, boolean lastPoint){
    Bitmap bm1 = null;
    Bitmap newBitmap = null;

    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);
    float width = bounds.width();
    float height =bounds.height();
    float radius;
    if (width > height){
        radius = height/4;
    }else{
        radius = width/4;
    }
    Paint paint1 = new Paint();
    paint1.setColor(Color.GREEN);
    paint1.setStrokeWidth(5);   
    paint1.setStyle(Paint.Style.FILL);
    float center_x, center_y;
    center_x = width/4;
    center_y = height/4;
    final RectF rect = new RectF();
    rect.set(center_x - radius, 
            center_y - radius, 
            center_x + radius, 
            center_y + radius);
    Canvas canvas2 = new Canvas();
    canvas2.drawRoundRect(rect, 0, 0, paint);
    canvas2.drawText(text, 0, 0, paint);
    return newBitmap;
     }

我的问题是如何将此canvas2转换为位图图像?和图像具有文本边界的大小,   看起来像a sample which i need

2 个答案:

答案 0 :(得分:1)

你可以创建一个位图,然后在该位图上调用draw,如下所示:

newBitmap = Bitmap.createBitmap(rect.width, rect.height, Bitmap.Config.ARGB_8888);
Canvas canvas2 = new Canvas(newBitmap);

答案 1 :(得分:1)

要将画布转换为位图,请执行以下操作:

public Bitmap convertCanvasToBitmap(int width , int height) {
        Bitmap drawnBitmap = null;

        try {
            drawnBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);

            Canvas canvas = new Canvas(drawnBitmap);
// now draw anything you want to the canvas 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return drawnBitmap;
}

所以这个想法只是将位图传递给画布,用画布绘制它将被绘制到你的位图中。

请参阅此答案here,了解如何处理位图中的文字大小。

请给我一些反馈

希望有所帮助。