我被困在这将近一个月了。我在我的 android 代码中有一个使用“afreechart”的完美图表,但是,该库似乎还不支持将图表导出为图像(因为它基于“jfreechart”,而这个可以完成)。
我尝试获取图 TableView ,将其转换为 Canvas 并使用位图库的压缩功能进行保存,但每次尝试此操作时,我都会得到一个全黑的图像。我尝试了同样的方法,它适用于我代码的其他 View (简单 View ,如 linearlayout 和 relativelayout)。
之后,我尝试创建一个例程来制作图表 Activity 的屏幕截图,然后关闭该 Activity 。但是我找不到通过代码来做到这一点的方法,我得到的最接近的方法是使用 monkeyrunner。
所以我放弃了这个想法并尝试寻找其他库,例如“kichart”、“achartengine”等,但它们似乎都无法胜任,我吓坏了,我认为将图表导出为图像并不难……有什么想法吗?
当我为布局设置背景颜色时,返回的图像是一个具有背景颜色的完整矩形,因此它获取的是布局,而不是图表。
我的代码:
package com.kichart;
import java.io.File;
import java.io.FileOutputStream;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
public class Main extends Activity {
LinearLayout ll;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
float[] values = new float[] { 2.0f,1.5f, 2.5f, 1.0f , 3.0f };
String[] verlabels = new String[] { "great", "ok", "bad" };
String[] horlabels = new String[] { "today", "tomorrow", "next week", "next month" };
GraphView graphView = new GraphView(this, values, "GraphViewDemo",horlabels, verlabels, GraphView.BAR);
ll = new LinearLayout(this);
ll.addView(graphView);
Draw2d d = new Draw2d(this);
setContentView(d);
//setContentView(graphView);
}
public class Draw2d extends View {
public Draw2d(Context context) {
super(context);
setDrawingCacheEnabled(true);
}
@Override
protected void onDraw(Canvas c) {
ll.setBackgroundColor(Color.WHITE);
ll.measure(MeasureSpec.getSize(ll.getWidth()), MeasureSpec.getSize(ll.getHeight()));
ll.layout(400, 400, 400, 400);
ll.draw(c);
try {
getDrawingCache().compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(new File("/mnt/sdcard/graph2.png")));
} catch (Exception e) {
Log.e("Error--------->", e.toString());
}
super.onDraw(c);
}
}
}
最佳答案
您可以通过以下方式从 View 中获取图像位图:
Bitmap bitmap;
chart.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(chart.getDrawingCache());
chart.setDrawingCacheEnabled(false);
如果您无法在图表上调用 getDrawingCache,请尝试将其置于 RelativeLayout 之类的布局中。并在布局上调用它。
之后你可以将它保存为图片..
如果图像仍然是黑色,您需要确保在获取位图之前创建了图表。
希望对你有帮助
关于android - 在 Android 中将图表导出为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13068495/