2014-02-24 28 views
0

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

我已经尝试过一个,下面给出。

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

回答

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以了解如何处理位图中的文字大小。

请给我一些反馈

希望有所帮助。

+0

哦......但这个尺寸太大了吧?这里的大小是400X400 ..我需要根据文本大小的位图大小... – ranjith

+0

您可以根据需要更改大小 –

+0

请检查我的更新回答 –

1

你可以创建一个位图,然后调用汲取该位图,这样的事情:

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

yaa我试过这个。但是非常小,就像一个点。 – ranjith

+0

我需要绘制位图图像,给定文本,因为图像需要基于文本长度的宽度和高度... – ranjith

+0

您需要先测量文本,并根据测量的大小创建位图,然后在画布上绘制,你坚持哪一步? – bladefury

相关问题