将图表另存为MPAndroidChart中的图像

时间:2015-04-24 11:19:45

标签: android mpandroidchart save-image

我正在使用MPAndroidChart渲染各种图表。我想添加将图表保存为图库的功能。我在操作栏中添加了一个图标以使用此功能,但图像不会保存到图库中。

代码如下:

<item android:id="@+id/save"
    android:icon="@drawable/ic_action_accept"
    android:title="@string/save"
    app:showAsAction="always"/>
@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);
    }
}

2 个答案:

答案 0 :(得分:4)

来自 How to programatically take a screenshot on Android?

// 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();
}

答案 1 :(得分:1)

使用Kotlin扩展,我可以这样实现:

//create a bitmap using view height and width to draw to it
fun View.getBitmap(): Bitmap = Bitmap.createBitmap(measuredWidth, measuredHeight, Bitmap.Config.ARGB_8888).also {
    //create a canvas for this bitmap (it)
    Canvas(it).apply {
        //if the view has a background, draw it to the canvas, else draw a white screen 
        //because canvas default background is black
        background?.draw(this) ?: drawColor(Color.WHITE)
        //draw the view to the canvas
        draw(this)
    }
}

我使用measuredWidth和Height的原因是因为当您具有可滚动视图或ViewGroup时,屏幕截图被裁剪了。