オフラインでインフレートしたViewのBitmapを得るには?

572 views
Skip to first unread message

Ishikawa Hiromi

unread,
Dec 4, 2010, 1:42:18 AM12/4/10
to Android SDK
こんにちは、石川と申します。

今、表題の件の実装方法で非常に悩んでおります。
やりたいことは、なんらかの事前にxmlで用意したレイアウトを画面に表示しないで、Bitmapを得たいということです。
画面に表示するのであれば、
以下のように、簡単に実現できるのですが、

View layout = View.inflate(ctx, R.layout.balloon, rootView);
layout.setDrawingCache(true);
Bitmap canvasBitmap = Bitmap.createBitmap(layout.getDrawingCache());
layout.setDrawingCache(true);

inflate の際のrootViewを指定しない状態では、Bitmapが作成されないようです。
そこで、以下のように実装してみたのですが、

View layout = View.inflate(ctx, R.layout.balloon, null);
Bitmap canvasBitmap = Bitmap.createBitmap(300, 300, Config.ARGB_4444);
Canvas canvas = new Canvas(canvasBitmap);
// layout.measure(canvas.getWidth(), canvas.getHeight());
// layout.forceLayout();
// layout.setWillNotDraw(false);
// layout.invalidate();
layout.draw(canvas);

drawがうまく実行されてくれないようです。
リスト上でコメントになっている部分は、drawのために実験試しに追加したコードですが、いずれもうまくいきません。
なにか良い方法はないでしょうか?

Ishikawa Hiromi

unread,
Dec 9, 2010, 3:42:25 AM12/9/10
to Android-SDK-Japan
自己解決しました。

ポイントは、view.measure(), view.layout(), view.invalidate() をこの順番かつ、適切な引数で先に
呼び出すこと。
ちなみに、getDrawingCache() を使用した方法は、子ビューのメソッドを呼び出したりした場合に、サイズがうまく設定されずに失敗し

うまくいかなかったです。


int measuredWidth = View.MeasureSpec.makeMeasureSpec(bitmapWidth,
View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(bitmapHeight,
View.MeasureSpec.EXACTLY);

// レイアウトのインフレート
View root = View.inflate(this, R.layout.balloon, null);

// 子ビューのプロパティ変更
((TextView)root.findViewById(R.id.TextView01)).setText("オフスクリーンイメー
ジ");
((Button)root.findViewById(R.id.Button01)).setText("ボタン");

// オフラインビットマップ作成
Bitmap bmp = Bitmap.createBitmap(bitmapWidth, bitmapHeight,
Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);

// オフラインビットマップにビューを描画
root.measure(measuredWidth, measuredHeight);
root.layout(0, 0, measuredWidth, measuredHeight);
root.invalidate();
root.draw(canvas);

Reply all
Reply to author
Forward
0 new messages