如何在图像视图android上绘制文本

时间:2014-04-24 16:10:08

标签: java android image bitmap

我有一个用于计算手机使用时间的应用,您可以在社交网络上分享,而不是正常gettext()我想将结果放在图像上并将其保存到手机中。如何创建可以保存到包含自定义文本的手机的图像?

2 个答案:

答案 0 :(得分:1)

您要做的是绘制一个链接到位图的Canvas,然后保存位图。这里有一些代码,你应该能够串起来使它工作。请注意,您必须在getBitmap()函数中将画布添加到画布。

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();
}

答案 1 :(得分:1)

首先将布局转换为位图:

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);

现在您可以将其保存到文件中:

FileOutputStream fos = new FileOutputStream(fileName, false);

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

fos.flush();
fos.close();