I'm trying to get the text input from the user and draw it on the image using Canvas but the image is saved without what was supposed to be drawn. Right now, I'm just trying to get the text on the Image before I worry about the font, colour, styles, etc.

This is my code:

 public void createBitmapAndSave(ImageView img){
        BitmapDrawable bitmapDrawable = ((BitmapDrawable) img.getDrawable());
        Bitmap bitmap = bitmapDrawable.getBitmap();
        Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);

        Canvas canvas = new Canvas(mutableBitmap);
        Paint paint = new Paint();
        paint.setShadowLayer(10f, 10f, 10f, Color.BLACK);

        String topText = topTextView.getText().toString();
        String bottomText = bottomTextView.getText().toString();

        canvas.drawText(topText, 0, 0, paint);
        canvas.drawText(bottomText, 50, 50, paint);

        File file;
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);

        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath();
        file = new File(path + "/SimpliMeme/" + timeStamp + "-" + counter + ".jpg");

            OutputStream stream = new FileOutputStream(file);
            Toast.makeText(getContext(), "Meme Saved", Toast.LENGTH_SHORT).show();
        catch (IOException e){ e.printStackTrace();}

        Uri contentUri = Uri.fromFile(file);

At the moment, I only have the 2 .drawText() implementations based on the examples that I've seen in other SO posts. My assumption is that the text isn't visible and no changes are made to the image because I haven't provided the paint object with any attributes.

      • 1
    • @EugenPechanec That's what I was wondering. Can't I draw text with the default font and color? Is the paint object a must to draw anything?
      • 1
    • @EugenPechanec Check the new code now. I've added attributes to the paint object and yet nothing is drawn on the bitmap.
      • 1
    • Is the paint object a must to draw anything? Yeah, that's the whole point of the class. Just read the docs: The Paint class holds the style and color information about how to draw geometries, text and bitmaps. As for nothing is drawn on the bitmap You changed mutableBitmap and saved bitmap, this is why you see no changes.

The main issue why you see no changes is that you make changes to mutableBitmap but save the original bitmap to disk.

This can be avoided by joining the first two (or even three) statements together:

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

You didn't need the orginal bitmap anywhere else, this effectively prevents you from making the mistake. Don't do what you don't need to do.

Some tips:

  • 1
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions