【问题标题】:Converting String to Bitmap (android)将字符串转换为位图 (android)
【发布时间】:2015-12-09 01:38:45
【问题描述】:

您好,我想将 String 转换为 Bitmap,一切都很好,但我不知道如何将结果 Image 设置为适合文本。 我怎样才能做到这一点 ? 这是我的代码:

public Bitmap textAsBitmap(String text, float textSize, float stroke,
                           int color, Typeface typeface) {

    TextPaint paint = new TextPaint();
    paint.setColor(color);
    paint.setTextSize(textSize);
    paint.setStrokeWidth(stroke);
    paint.setTypeface(typeface);

    paint.setAntiAlias(true);
    paint.setTextAlign(Paint.Align.LEFT);

    float baseline = (int) (-paint.ascent() + 3f);

    StaticLayout staticLayout = new StaticLayout(text, 0, text.length(),
            paint, 435, android.text.Layout.Alignment.ALIGN_NORMAL, 1.0f,
            1.0f, false);

    int linecount = staticLayout.getLineCount();




    int height = (int) (baseline + paint.descent() + 3) * linecount + 10;

    Bitmap image = Bitmap
            .createBitmap(****MY WIDTH***, height, Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(image);
    canvas.drawARGB(0xFF, 0xFF, 0xFF, 0xFF);

    staticLayout.draw(canvas);

    return image;

}

我什至试过这个,但它不能正常工作:

final Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);


    Bitmap image = Bitmap
            .createBitmap(bounds.width(), height, Bitmap.Config.ARGB_8888);

请帮忙!

【问题讨论】:

    标签: android string bitmap width paint


    【解决方案1】:

    你应该试试这个

     public String BitMapToString(Bitmap bitmap) {
        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArray);
        byte[] b = byteArray.toByteArray();
        String result = Base64.encodeToString(b, Base64.DEFAULT);
        return result;
    }
    

    希望这会有所帮助!!!

    【讨论】:

    • 这行得通,但 OP 要求与您的答案完全相反。
    【解决方案2】:

    试试这个:

    canvas.drawColor(Color.BLUE);
    

    代替:

    canvas.drawARGB(0xFF, 0xFF, 0xFF, 0xFF);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-06
      相关资源
      最近更新 更多