MPAndroidChart - getChartBitmap 不显示折线图



我正在尝试生成并共享使用MPAndroidChart构建的图表的图像。 我正在使用ShareIntent,这是onCreateOptionsMenu方法:

public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file
getMenuInflater().inflate(R.menu.share_menu, menu);
// Locate share item with ShareActionProvider
MenuItem shareItem = menu.findItem(R.id.item_share);
// Fetch and store ShareActionProvider
shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
Bitmap chartBitmap = chart.getChartBitmap();
File imagesDirectory = new File(getFilesDir(), "images");
if (!imagesDirectory.isDirectory() || !imagesDirectory.exists()) {
imagesDirectory.mkdir();
}
File bitmapFile = new File(imagesDirectory, chartName.concat(".jpeg"));
if (!bitmapFile.exists()) {
try {
bitmapFile.createNewFile();
} catch (IOException e){
e.printStackTrace();
}
}
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(bitmapFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Uri contentUri = FileProvider.getUriForFile(getBaseContext(), "com.mycompany", bitmapFile);
chartBitmap.compress(Bitmap.CompressFormat.JPEG, 20, outputStream);
Intent shareImageIntent = new Intent(Intent.ACTION_SEND);
shareImageIntent.setType("image/jpeg");
shareImageIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
shareImageIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
setShareIntent(shareImageIntent);
// Return true to display menu
return true;
}

在这里,我按照MPAndroidChart维基中的建议从图表中获取位图

getChartBitmap():返回表示图表的位图对象,此位图始终包含图表的最新绘制状态。

Bitmap chartBitmap = chart.getChartBitmap();

然后,按照 Android 文档中的建议,我使用FileProvider来共享图像; 这是我在AndroidManifest.xml中声明它的地方:

<provider
android:authorities="com.mycompany"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/images_path"/>
</provider>

这是我指定包含我需要共享的文件的目录的地方

<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="sharedImages" path="images/"/>
</paths>

这是我想分享的图表屏幕,但这是实际共享的图像。

为什么图表的线条不见了?

我不知道,但你可以从布局中获取位图,包括图表, 前任:

view.setDrawingCacheEnabled(true)
view.buildDrawingCache()
Bitmap bm = view.getDrawingCache()

我解决了!这是我的错,但在这种情况下,库并不完美。 问题是我在onCreateOptionsMenu中调用getChartBitmap,一旦我导航到该活动,它就会执行。

MPAndroidChart允许您添加一个缓慢显示图表的动画;当我调用getChartBitmap时,动画仍在进行,所以我看不到图表线,因为它尚未加载。

我禁用了动画,现在一切正常。如果有人知道使用图表线获取图像并保留动画的方法,请告诉我。

最新更新