【问题标题】:How to convert the text to bitmap in Android如何在Android中将文本转换为位图
【发布时间】:2014-02-24 05:47:05
【问题描述】:

请帮我画一个圆角矩形作为背景的文本。我必须在画布上绘制许多文本,并且文本具有圆形背景。所以我正在尝试编写一个函数“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 转换为位图图像?并且图像具有文本边界的大小, 看起来像

【问题讨论】:

    标签: android bitmap android-canvas draw bitmapfactory


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

    请给我一些反馈

    希望对您有所帮助。

    【讨论】:

    • 哦...但是这个尺寸太大了,对吧?这里的大小是 400X400.. 我需要基于文本大小的位图大小...
    • 你随意改变大小
    • 但是我们如何从文本中获取宽度和高度我使用 Rect 对象来获取边界但它不起作用
    • 您的问题是如何将此 canvas2 转换为位图图像,而不是如何从文本中获取宽度和高度
    • 对不起,我的确切问题是这个问题,即如何将canvas2转换为位图,但我需要尺寸有限的位图,而不是像400X400
    【解决方案2】:

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

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

    【讨论】:

    • 是的,我试过这个。但它非常小,就像一个点。
    • 我需要用给定的文本绘制位图图像,因为图像需要根据文本长度的宽度和高度...
    • 你需要先测量文本,根据测量的大小创建位图,然后在画布上绘制,你卡在哪一步了?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    相关资源
    最近更新 更多