views:

245

answers:

2

I want to get the bitmap that is drawn when a textview is displayed but without displaying the textview in the activity. something like this:

TextView t = new TextView(this);
t.forceToDrawItself();
Bitmap b=t.getViewBitmap();

how is this possible?

+1  A: 

View#draw(Canvas) will draw the entire view into the given Canvas. You can use the constructor Canvas(Bitmap) to create a Canvas that draws into the given Bitmap.

Create a bitmap of the desired size with Bitmap#createBitmap(int, int, Bitmap.Config), wrap it in a canvas, and pass it to your view's draw method.

adamp
ok works fine. now i have the problem that i have to set the size of the view manually.. is there a method to calc the default size of a view? like t.initSize(); ?
Sponge
Take a look at the "Layout" section of the View class documentation. (http://developer.android.com/reference/android/view/View.html) You will want to call View#measure with MeasureSpecs for width and height.
adamp
A: 

Hi Sponge & adamp,

Now I also need to get bitmap from text view, but I failed use the view.draw(Canvas) method.

Here is my code:

class MyView extends View{

......
    public MyView(Context context) {
        super(context);

        mBackDraw = Bitmap.createBitmap(100, 100,
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(mBackDraw);
        // TODO Auto-generated constructor stub
        mText = new TextView(context);
        mText.setText("1 line\n 2line \n \n \n 3fliener");
        mText.draw(canvas);
    }

@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();
        canvas.drawColor(Color.YELLOW);
        canvas.drawBitmap(mBackDraw, 0, 0, PAINT);
        canvas.restore();
    }

}

This is just a test code. I create the bitmap "mBackDraw", and draw the textview to it. Then in the MyView's onDraw method, I draw the bitmap using "canvas.drawBitmap(mBackDraw, 0, 0, PAINT);". I except that the text view's content should be drawn, but nothing on the screen.

Will you please tell me where I get wrong?

Thanks a lot!!

Rick
i postet the code i am using here:http://stackoverflow.com/questions/2801116/converting-a-view-to-bitmap-without-displaying-it-in-android/3036736#3036736
Sponge
It works, thanks so much. Seems the reason is I didn't set the layout parameters.
Rick