Question

I have an app that calculate time of phone usage and you can share it on social networks, instead of normal gettext() I want to put the results on an image and save it to phone. How can I create an image that I can save to the phone that includes custom text?

Was it helpful?

Solution

What you want to do is to paint to a Canvas that's linked to a Bitmap, and save the bitmap. Here's a few bits of code that you should be able to string together to make it work. Note that you'll have to still add the paining to the canvas, in the getBitmap() function.

private Bitmap getBitmap() {
    Bitmap bitmap = Bitmap.createBitmap(mPieToss.getWidth(),
            mPieToss.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    // Draw things to your canvas. They will be included as your BitMap, which is saved later on


    return bitmap;
}

public void save() {
    Bitmap bitmap = getBitmap();

    File path = Environment
            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
            .format(new Date());

    String filename = "Imagen_" + timestamp + ".jpg";
    File file = new File(path, filename);
    FileOutputStream stream;
    // This can fail if the external storage is mounted via USB
    try {
        stream = new FileOutputStream(file);
        bitmap.compress(CompressFormat.PNG, 100, stream);
        stream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    mUri = Uri.fromFile(file);

    bitmap.recycle();
}

OTHER TIPS

First of all convert your layout to bitmap:

View contentLayout; // your layout with bavkground image and TextView
Bitmap bitmap = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);

content.draw(canvas);

Now you can save it to the file:

FileOutputStream fos = new FileOutputStream(fileName, false);

bitmap.compress(Bitmap.CompressFormat.PNG, 75, fos);

fos.flush();
fos.close();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top