Search code examples
androidbitmaphardware-accelerationandroid-graphview

Illegal State Exception when trying to generate an image from a GraphView


I am trying to generate a image from a GrapView and I get the following error, despite I've set hardwareAccelerated to true:

java.lang.IllegalStateException: GraphView must be used in hardware accelerated mode.You can use android:hardwareAccelerated="true" on your activity. Read this for more info:https://developer.android.com/guide/topics/graphics/hardware-accel.html

Here is the code where I get the error:

graphView.addSeries(RepresentationHelper.getHashMapnewAPI().get(object.getName()));
            graphView.setTitle("");

            //setting y label for bounds with the min and max value obtained from the request
            graphView.getViewport().setYAxisBoundsManual(true);
            double low = graphView.getSeries().get(0).getLowestValueY();
            double high = graphView.getSeries().get(0).getHighestValueY();
            graphView.getViewport().setMinY(low);
            graphView.getViewport().setMaxY(high);

            graphView.getGridLabelRenderer().setHorizontalLabelsVisible(false);
            graphView.getGridLabelRenderer().setVerticalLabelsVisible(false);
            graphView.getGridLabelRenderer().setHighlightZeroLines(false);
            graphView.getGridLabelRenderer().setGridColor(Color.WHITE);

            Bitmap bitmap;
            graphView.setDrawingCacheEnabled(true);
            bitmap = Bitmap.createBitmap(graphView.getDrawingCache());
            graphView.setDrawingCacheEnabled(false);

            ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView);
            //imageView.setImageDrawable(context.getResources().getDrawable(R.drawable.grafico_definitivo));
            imageView.setImageBitmap(bitmap);

Solution

  • You should try something like this:

    try {
                    Bitmap bitmap = Bitmap.createBitmap(graphView.getWidth(), graphView.getHeight(), Bitmap.Config.ARGB_8888);
                    Canvas canvas = new Canvas(bitmap) {
    
                        @Override
                        public boolean isHardwareAccelerated() {
                            return true;
                        }
                    };
    
                    graphView.draw(canvas);
                    RepresentationHelper.addBitmap(string, bitmap);
    
                    if (firstRequest) {
                        adapter.notifyDataSetChanged();
                        firstRequest = false;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
    

    And now, you have on bitmap the image of your graphView!!

    Hope this can help you!! :)