将文本视图(包括屏幕上的内容)转换为位图

时间:2011-02-18 15:22:29

标签: android view bitmap textview

我想保存(导出)MyView的内容,它将TextView扩展为位图。

我按照代码:[this] [1]。

当文字大小很小时,它可以正常工作。

但是当有很多文本,而且有些内容不在屏幕上时,我得到的只是屏幕上显示的内容。

然后我在代码中添加了“布局”:

private class MyView extends TextView{
    public MyView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public Bitmap export(){
        Layout l = getLayout();
        int width = l.getWidth() + getPaddingLeft() + getPaddingRight();
        int height = l.getHeight() + getPaddingTop() + getPaddingBottom();

        Bitmap viewBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(viewBitmap);


        setCursorVisible(false);
        layout(0, 0, width, height);
        draw(canvas);

        setCursorVisible(true);
        return viewBitmap;
    }
}

现在发生了一件奇怪的事情:

我第一次调用“导出”(我使用选项键来执行此操作),我只在屏幕上显示内容。

当我再次调用“导出”时,我获得了完整的内容,包括屏幕外的内容。

为什么?

如何“导出”一个视图,包括内容无法在屏幕上显示?

谢谢!

[1]:http://www.techjini.com/blog/2010/02/10/quicktip-how-to-convert-a-view-to-an-image-android/这个

3 个答案:

答案 0 :(得分:1)

我发现了一种更简单的方法: 将TextView放在ScrollView中。 现在myTextView.draw(画布)将绘制所有文本。

答案 1 :(得分:0)

我认为你应该从高度宽度减去填充而不是添加它。添加它会给你一个比屏幕大的区域。

答案 2 :(得分:0)

我用这种方式解决了这个问题(奇怪但有效):

public Bitmap export(){
    //...
    LayoutParams lp = getLayoutParams();
    int old_width = lp.width;
    int old_height = lp.height;
    int old_scroll_x = getScrollX();
    int old_scroll_y = getScrollY();
    lp.width = width;
    lp.height = height;
    layout(0, 0, width, height);
    scrollTo(0, 0);
    draw(canvas);
    lp.width = old_width;
    lp.height = old_height;
    setLayoutParams(lp);
    scrollTo(old_scroll_x, old_scroll_y);
    //...

}