LoginSignup
31
30

More than 5 years have passed since last update.

画面に配置せずにViewからBitmapを生成する

Posted at

やりたいこと

  • アプリ内で動的にBitmapを生成したい
  • そのBitmapの中に動的にテキストとか入れたい
    • →Viewから動的にBitmapをつくろう

解決法

ViewからBitmapを生成すればOK(http://stackoverflow.com/a/3036736/4804134)

public void createBitmap() {

  // ビューを生成
  // 例として、TextViewに動的にテキストを入れる
  View v = LayoutInflator.from(this).inflate(R.layout.hoge, null);
  TextView tv = (TextView)v.findViewById(R.id.textView);
  tv.setText("ここに動的にテキストを入れる");

  // 画面内に配置してないので、measureを読んでからBitmapに書き込む
  if (v.getMeasuredHeight() <= 0) {
    v.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    Bitmap b = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
    v.draw(c);
    return b;
  }
}
31
30
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
30