Android:从动态视图生成图像

时间:2014-04-02 11:04:08

标签: android

我想动态生成图表,并将图表保存为图像以供以后在应用程序中使用, 无需在屏幕上显示图表, 我可以使用AFreeChart库生成图表,图表实际上是View类的子视图, 我想使用以下代码从视图中获取位图,但方法getDrawingCache()始终返回null,

    // Retrieve the chart generated using AFreeChart Library
    // PressureChart is a sub view of View class
     PressureChart mView = new PressureChart(this);

     mView.setDrawingCacheEnabled(true);
     mView.buildDrawingCache(true);
     Bitmap b = Bitmap.createBitmap(mView.getDrawingCache());
     mView.setDrawingCacheEnabled(false); // clear drawing cache

3 个答案:

答案 0 :(得分:1)

你想得到像这样的位图..它完美的工作 你需要像方法那样传递视图。

Bitmap mBitmap = getBitmapFromView(viewname);

然后使用位图来存储图像..

public static Bitmap getBitmapFromView(View view) {
    // Define a bitmap with the same size as the view

    int FixWidth = 800;
    int FixHeight = 800;
    int bit_width = 0;
    int bit_height = 0;

    bit_width = mImageView.getDrawable().getIntrinsicWidth();
    bit_height = mImageView.getDrawable().getIntrinsicHeight();

    if (bit_width > FixWidth) {
        bit_width = FixWidth;
    }

    if (bit_height > FixHeight) {
        bit_height = FixHeight;
    }

    float ratio = Math.min((float) 800 / bit_width, (float) 800 / bit_height);
    int width = Math.round((float) ratio * bit_width);
    int height = Math.round((float) ratio * bit_height);

    Bitmap returnedBitmap = Bitmap.createBitmap(width * 2, height * (int)2.5f, Bitmap.Config.ARGB_8888);
    // Bind a canvas to it
    Canvas canvas = new Canvas(returnedBitmap);
    // Get the view's background
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        // has background drawable, then draw it on the canvas
        bgDrawable.draw(canvas);
    else
        // does not have background drawable, then draw white background on the canvas
        canvas.drawColor(Color.WHITE);
    // draw the view on the canvas
    view.draw(canvas);
    // return the bitmap
    return returnedBitmap;
}

答案 1 :(得分:0)

你可以试试这个..

view上添加该图表FrameLayout,然后使用..

    feamelayout.setDrawingCacheEnabled(true);
    Bitmap bm = f.getDrawingCache();

保存图片..

答案 2 :(得分:0)

之前放一些延迟(1/2秒) 位图b = Bitmap.createBitmap(mView.getDrawingCache()); mView.setDrawingCacheEnabled(假); //清除图纸缓存

使用一些计时器,这将有助于大多数情况,因为我们尝试在准备之前捕获图像。

您的代码看起来像

// Retrieve the chart generated using AFreeChart Library
    // PressureChart is a sub view of View class
     PressureChart mView = new PressureChart(this);

     mView.setDrawingCacheEnabled(true);
     mView.buildDrawingCache(true);
    new Timer().schedule(new TimerTask() {          
        @Override
        public void run() {
            // this code will be executed after 2 seconds  
                 Bitmap b = Bitmap.createBitmap(mView.getDrawingCache());
                 mView.setDrawingCacheEnabled(false); // clear drawing cache     
        }

}, 2000);