I'm trying to make an app for create custom cards. I'd like to add some text over a custom background (a jpg image).
What is the best way of doing it? I'd need to show the user a preview of the card before send it to the server.
Thanks
Use below code to achieve your requirement
Bitmap src = BitmapFactory.decodeResource(getResources(), R.drawable.yourimage); // the original file yourimage.jpg i added in resources
Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);
String yourText = "My custom Text adding to Image";
Canvas cs = new Canvas(dest);
Paint tPaint = new Paint();
tPaint.setTextSize(35);
tPaint.setColor(Color.BLUE);
tPaint.setStyle(Style.FILL);
cs.drawBitmap(src, 0f, 0f, null);
float height = tPaint.measureText("yY");
float width = tPaint.measureText(yourText);
float x_coord = (src.getWidth() - width)/2;
cs.drawText(yourText, x_coord, height+15f, tPaint); // 15f is to put space between top edge and the text, if you want to change it, you can
try {
dest.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("/sdcard/ImageAfterAddingText.jpg")));
// dest is Bitmap, if you want to preview the final image, you can display it on screen also before saving
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You have to use below permission in manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For my device the path is /sdcard
to access external SD card, it may vary for other devices. Some devices may have /mnt/sdcard
may be it is for internal sd cards. Just check it while before using this code.
Actually I wrote the above code for some other question, which required time stamp on photo after captured from camera. I gave you the same solution with a little modifications for your specific requirement.
I hope you can understand this. If you have any doubts regarding code feel free to ask.
I am not sure this is the best solution, but it might help you.
Step1: Create a relative layout (or any other layout) and set your image as its background.
Step2: Now add a TextView with width and height as match_parent
and gravity set as top|center_horizontal
.
Step3: Now add another button or any other layout control which will trigger the user confirmation. (You should place this control outside the Relative layout).
Step4: If user has confirmed the image then you can take screenshot of your relative layout via following code:
v1.setDrawingCacheEnabled(true); //v1 is the object of your Relative layout
Bitmap bm = v1.getDrawingCache();
if (bm != null) {
//TODO: write the code for saving the image.
Toast toast = Toast.makeText(YourActivity.this, "image saved",
Toast.LENGTH_LONG);
toast.show();
} else {
Toast toast = Toast.makeText(YourActivity.this,
"No image saved.", Toast.LENGTH_LONG);
toast.show();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With