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.setColor(Color.BLUE);
paint.setTextSize(200);
paint.setStyle(Paint.Style.FILL);
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");
file.getParentFile().mkdir();
try{
OutputStream stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
Toast.makeText(getContext(), "Meme Saved", Toast.LENGTH_SHORT).show();
}
catch (IOException e){ e.printStackTrace();}
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
Objects.requireNonNull(getContext()).sendBroadcast(mediaScanIntent);
counter++;
}
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.
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:
StaticLayout
.