android achartengine : trying to export graph as image throws exception

橙三吉。 提交于 2019-12-02 08:04:33

问题


in an android app, am attempting to export the graph (which I drew using achartengine) as Bitmap object via this code

public static Bitmap loadBitmapFromView(Context context, View view) {

    Bitmap bitmap;

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPurgeable = true;
    options.inInputShareable = true;

    Bitmap dummy = null;
    try {
        dummy = BitmapFactory.decodeStream(context.getAssets().open("icon_add.png"), new Rect(-1,-1,-1,-1), options);
    } catch (IOException e) {
        e.printStackTrace();
    }
     bitmap = Bitmap.createBitmap(view.getLayoutParams().width,
        view.getLayoutParams().height, Bitmap.Config.ARGB_4444);
    Canvas c = new Canvas(bitmap);
    view.layout(0, 0, view.getLayoutParams().width, view.getLayoutParams().height);
    view.draw(c);
    c = null;

    return bitmap;
}

and am calling this method as:

loadBitmapFromView(getApplicationContext(), this.graphView);

where graphView is the object of type GraphicalView

But this is throwing the exception

java.lang.IllegalArgumentException: width and height must be > 0

at this line

bitmap = Bitmap.createBitmap(view.getLayoutParams().width,
        view.getLayoutParams().height, Bitmap.Config.ARGB_4444);

can someone please help?


回答1:


Per http://developer.android.com/reference/android/view/View.html#getLayoutParams() that method returns the

... layout parameters. These supply parameters to the parent of this view specifying how it should be arranged.

i.e. these are inputs to the layout computation:

LayoutParams ... describes how big the view wants to be for both width and height. For each dimension, it can specify one of an exact number, MATCH_PARENT, WRAP_CONTENT

You need the actual View size, that is, the result of the layout computation.

If this View is already laid out on screen, then view.getWidth() and view.getHeight() should return its actual size. In that case, calling view.layout(...) may put the displayed View in a weird state that you should restore, and again you want to pass actual size info, not layout params.

If this View is not on screen, then view.measure(widthMeasureSpec, heightMeasureSpec) is supposed to be called before view.layout(...). Do read the View docs.



来源:https://stackoverflow.com/questions/22135536/android-achartengine-trying-to-export-graph-as-image-throws-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!