Arj*_*sar 2 android save-image mpandroidchart
我正在使用 MPAndroidChart 来呈现各种图表。我想添加将图表作为图像保存到图库的功能。我在操作栏中添加了一个图标以使用此功能,但图像未保存到图库中。
代码如下:
<item android:id="@+id/save"
android:icon="@drawable/ic_action_accept"
android:title="@string/save"
app:showAsAction="always"/>
Run Code Online (Sandbox Code Playgroud)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.save :
mlineChart.saveToGallery("Chart",50);
return true;
case R.id.action_settings :
return true;
default: return super.onOptionsItemSelected(item);
}
}
Run Code Online (Sandbox Code Playgroud)
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + ACCUWX.IMAGE_APPEND;
// create bitmap screen capture
Bitmap bitmap;
View v1 = mWebview.getRootView(); // take the view from your webview
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
OutputStream fout = null;
imageFile = new File(mPath);
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
更新
感谢 tamim 指出这个弃用。这是更新的解决方案
public void setDrawingCacheEnabled(启用布尔值)
此方法在 API 级别 28 中已弃用。随着 API 11 中硬件加速渲染的引入,视图绘制缓存在很大程度上已过时。使用硬件加速,中间缓存层在很大程度上是不必要的,并且很容易导致性能的净损失由于创建和更新图层的成本。在缓存层有用的极少数情况下,例如对于 alpha 动画, setLayerType(int, android.graphics.Paint) 使用硬件渲染来处理它。对于视图层次结构的一小部分或单个视图的软件渲染快照,建议从位图或图片创建画布并在视图上调用 draw(android.graphics.Canvas)。但是,不鼓励使用这些软件渲染的用法,并且它们与纯硬件渲染功能(例如 Config.HARDWARE 位图、实时阴影和轮廓剪裁)存在兼容性问题。对于反馈报告或单元测试的 UI 屏幕截图,建议使用 PixelCopy API。
因此,根据建议,使用PixelCopy来获取UI的屏幕截图/快照。它在 API 级别 24 及以上可用
PixelCopy.request(surfaceViewObject,BitmapDest,listener,new Handler());
Run Code Online (Sandbox Code Playgroud)
在哪里,
surfaceViewObject 是表面视图的对象
BitmapDest 是保存图片的位图对象,不能为空
侦听器是 OnPixelCopyFinishedListener
有关更多信息,请参阅Pixel Copy Android 文档
| 归档时间: |
|
| 查看次数: |
5214 次 |
| 最近记录: |