将视图转换为位图而不在Android中显示(使用setHorizo​​ntallyScrollyng)?

时间:2014-08-25 16:26:07

标签: android bitmap

在我的代码中,我有一个带有许多TextView(如表)的LinearLayout。我尝试将其转换为Bitmap。有我的代码:

    public static Bitmap convertToBitmap(LinearLayout view){
    view.measure(LinearLayout.LayoutParams.WRAP_CONTENT,
                 LinearLayout.LayoutParams.WRAP_CONTENT);
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
                                        view.getHeight(),
                                        Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(bitmap);
    view.draw(c);
    return bitmap;
}

但是,有一个问题。 视图女巫setSingleLine(true)不在位图中显示文本。 确切地说,问题在于setHorizo​​ntallyScrolling(true),它在setSingleLine代码中调用... 我尝试使用.setScrollTo(X),但是X必须是什么。 X = 0 - 不起作用。

有没有,谁知道如何解决它?

编辑:TextViews具有固定的宽度。 编辑:问题仅适用于Gravity = Center的TextView。随着重力离开,一切都好。

1 个答案:

答案 0 :(得分:1)

试试其中一个代码?它与你上面发布的有点不同。

/**
 * this actually also provided by Romain Guy, but let's try another for performance improvements
 */
public static Bitmap getBitmapFromView(View view, int width, int height) {
    view.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
            View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

    // Build the Drawing Cache
    view.buildDrawingCache();

    // Create Bitmap
    Bitmap drawingCache = view.getDrawingCache();
    if (drawingCache == null) {
        return null;
    }

    Bitmap bitmap = Bitmap.createBitmap(drawingCache);
    drawingCache.recycle();
    view.setDrawingCacheEnabled(false);
    return bitmap;
}

/**
 * This method provided by Romain Guy, so it should do the job better, especially it includes case for listViews
 */
public static Bitmap getBitmapFromView(View view, int width, int height) {

    //Pre-measure the view so that height and width don't remain null.
    view.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));
    //Assign a size and position to the view and all of its descendants
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

    // Create bitmap
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);

    //Create a canvas with the specified bitmap to draw into
    Canvas canvas = new Canvas(bitmap);

    // if it's scrollView we get gull size
    canvas.translate(-view.getScrollX(), -view.getScrollY());
    //Render this view (and all of its children) to the given Canvas
    view.draw(canvas);
    return bitmap;
}