在imageview上添加文本并保存

时间:2013-01-05 10:56:19

标签: android android-layout android-canvas android-imageview android-image

我正在尝试创建一个向图像添加文本的应用程序。在这里,我的图像来自图库,文字由用户添加。为此我创建了我的布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativelayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<ImageView
    android:id="@+id/myImageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

<TextView
    android:id="@+id/myImageViewText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/myImageView"
    android:layout_alignLeft="@+id/myImageView"
    android:layout_alignRight="@+id/myImageView"
    android:layout_alignTop="@+id/myImageView"
    android:layout_margin="1dp"
    android:gravity="center"
    android:text="Hello"
    android:textColor="#000000" />

活动如下:

public class AddText extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.add_text);

    findViewById(R.id.relativelayout).setDrawingCacheEnabled(true);
    Bitmap finalImg = findViewById(R.id.relativelayout).getDrawingCache();

    String save_location = Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/texted";
    File dir = new File(save_location);
    if (!dir.exists())
        dir.mkdirs();
    File f = new File(dir, "tmp.jpg");
    FileOutputStream out;
    try {
        out = new FileOutputStream(f);
        finalImg.compress(Bitmap.CompressFormat.PNG, 90, out);

        out.flush();
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

现在我想用文字保存整个图像。用文本保存图像的方法是什么?

错误是:

enter image description here

2 个答案:

答案 0 :(得分:0)

您的布局应将启用的图形缓存设置为true。您可以通过设置器View.setDrawingCacheEnabled(true);进行设置然后您应该能够使用View检索View.getDrawingCache()的内容。该方法返回一个表示View内容的Bitmap实例。您可以使用Bitmap.compress(..)来存储它。

答案 1 :(得分:-1)

选择图像后,为用户提供编辑文本框,输入文本。而不是相对布局使用框架布局,以便文本将显示在图像上。

您必须将视图转换为位图

这是代码

 public static Bitmap loadBitmapFromView(View v)
 { 
Bitmap b = Bitmap.createBitmap(v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888); 
Canvas c = new Canvas(b); v.layout(0, 0, v.getLayoutParams().width,v.getLayoutParams().height); v.draw(c); 
return b;
 }