1

I have a text like this: <b style="color: rgb(255, 0, 0);">Test</b> which is given to Html.fromHtml call, which returns a Spanned used in a StaticLayout drawn on an Android Canvas bound to a Bitmap.

The image which is drawn contains this bold text. But the latter isn't colored in red, which altough is defined by the CSS inline style.

I know the option Html.FROM_HTML_OPTION_USE_CSS_COLORS exists, but (as I could implicitly read in the documentation) it doesn't have this purpose.

Sources

Nota: in the following code, mTextPaint.setColor(Color.WHITE); is commented. The text is painted in black, on a black blackground. But not in red. So the problem isn't that mTextPaint.setColor would override my CSS inline style color.

private BitmapDrawable addTextOnImage(BitmapDrawable bitmapDrawable) {

    Spanned caption = Html.fromHtml("<b style=\"color: rgb(255, 0, 0);\">Test</b>", Html.FROM_HTML_MODE_LEGACY);

    Bitmap bitmap_largest_image = bitmapDrawable.getBitmap().copy(Bitmap.Config.ARGB_8888, true);

    TextPaint mTextPaint = new TextPaint();
    //mTextPaint.setColor(Color.WHITE);
    mTextPaint.setTextSize(30);
    StaticLayout mTextLayout_caption = StaticLayout.Builder.obtain(caption, 0, caption.length(), mTextPaint, bitmap_largest_image.getWidth()).build();

    Paint backgrounds_paint = new Paint();
    backgrounds_paint.setColor(Color.BLACK);
    backgrounds_paint.setStyle(Paint.Style.FILL);

    Bitmap final_bitmap = Bitmap.createBitmap(bitmap_largest_image.getWidth(), mTextLayout_caption.getHeight() + bitmap_largest_image.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(final_bitmap);
    canvas.drawRect(0, 0, bitmap_largest_image.getWidth(), mTextLayout_caption.getHeight(), backgrounds_paint);
    mTextLayout_caption.draw(canvas);
    canvas.drawBitmap(Bitmap.createScaledBitmap(bitmap_largest_image, bitmap_largest_image.getWidth(), bitmap_largest_image.getHeight(), false),  0, mTextLayout_caption.getHeight(), new Paint());

    return new BitmapDrawable(getActivity().getResources(), final_bitmap);
}
JarsOfJam-Scheduler
  • 2,809
  • 3
  • 31
  • 70

0 Answers0