尝试为https://github.com/appsthatmatter/GraphView拍摄图表快照时获取IllegalStateException

时间:2017-01-29 11:36:12

标签: android android-graphview

我正在尝试拍摄GraphView的快照,但它给出了一个错误“GraphView必须在硬件加速模式下使用”。 我正在使用以下代码拍摄快照

Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); 
Canvas canvas = new Canvas(bitmap); 
view.draw(canvas);

另外,我已经在应用程序级别设置了android:hardwareAccelerated="true"

3 个答案:

答案 0 :(得分:1)

我用过这个:

dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  testCompile 'junit:junit:4.12'
 compile 'com.android.support:appcompat-v7:23.1.1'
 compile files('libs/GraphView-4.0.1.jar')
  compile 'com.jjoe64:graphview:4.1.0'
}

特别是

compile 'com.jjoe64:graphview:4.1.0'
这对我有所帮助。

答案 1 :(得分:1)

问题是最近版本中的GraphView包含其他条件 - 如果画布是否处于硬件加速模式:

GraphView.java https://github.com/appsthatmatter/GraphView/commit/0740de3e0a93633f7f168115b96edfdce156b19e

public class GraphView extends View {

    ...

    protected void drawGraphElements(Canvas canvas) {
        // must be in hardware accelerated mode
        if (android.os.Build.VERSION.SDK_INT >= 11 && !canvas.isHardwareAccelerated()) {
            throw new 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");
        }
        ...
    }

    ...
}

创建离屏画布时,它没有硬件加速模式。但是你可以为你的Canvas实例覆盖isHardwareAccelerated。使用此解决方法:

Bitmap bitmap = Bitmap.createBitmap(graphView.getWidth(), graphView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap) {
    @Override
    public boolean isHardwareAccelerated() {
        return true;
    }
};

// not it's work
graphView.draw(canvas);

// save somewhere
bitmap.compress(Bitmap.CompressFormat.JPEG, 100,  new FileOutputStream(imagePath));

答案 2 :(得分:0)

在最新版本4.2.2中,快照功能正常运行。您可以查看文档和示例项目:

http://www.android-graphview.org/take-snapshots/

这基本上是API调用:

// directly share it
graph.takeSnapshotAndShare(mActivity, "exampleGraph", "GraphViewSnapshot");

// get the bitmap
Bitmap bitmap = graph.takeSnapshot();