我正在开发一个 android 应用程序,它通过 tcp 获取图形值并实时连续地绘制图形。该应用程序必须每秒绘制 100 个像素/值,在 10 秒内完成一个 1000 像素宽度的图形。
我正在三星 Galaxy Tab 10.1 平板电脑上开发。
下面是主要的活动代码。我只是粘贴了必要的部分。
public class MainActivity extends Activity {
private MyGraph graph;
private Handler mHandler;
private Handler mHandler2;
private boolean running;
public static int counter=1;
private int limit=1000;
private class MyGraph extends View {
private Paint paintecg = new Paint();
private Paint paintdel = new Paint();
private Canvas canvas = new Canvas();
private Bitmap cache = Bitmap.createBitmap(1000,800, Bitmap.Config.ARGB_8888);
private float nextX; //next point in x axis
private float lastX=0;
private float nextY; // next point in y axis
private float lastY=150;
public MyGraph(Context context){
super(context);
paintecg.setStyle(Paint.Style.STROKE);
paintecg.setColor(Color.GREEN);
paintecg.setAntiAlias(true); paintecg.setStrokeWidth(2f);
paintdel.setStyle(Paint.Style.FILL_AND_STROKE);
paintdel.setColor(Color.BLACK);
}
public void onDraw(Canvas canvas) {
if (cache != null)
canvas.drawBitmap(cache, 0, 0, paintecg);
}
public void drawNext() {
canvas = new Canvas(cache);
nextX=lastX+1;
//adding new points to the graph
canvas.drawLine(lastX,valuearray_ecg[counter-1],nextX,valuearray_ecg[counter], paintecg);
//emptying next 25 pixels
canvas.drawRect(nextX, 0, nextX+25, 800, paintdel);
lastX=nextX;
if (nextX<limit) {
counter++;
}
else {
counter=1;
lastX=0;
}
postInvalidate();
}
}
}
这是在 oncreate() 方法中创建的处理程序:
LinearLayout graphView=(LinearLayout) findViewById(R.id.layout_graph);
graph = new MyGraph(this);
mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
graph.drawNext();
if (running)
mHandler.sendMessageDelayed(new Message(), 10);
return true;
}
});
graphView.addView(graph);
图形在 main.xml 中的布局内绘制
这样,当我将处理程序设置为 20 毫秒并且我的 x 轴步进为 2 像素时,它会在大约 15 秒内绘制 1000 像素。奇怪的是,如果我在应用程序运行时锁定和解锁设备,时间就会变得正常并绘制10 秒内 1000 个像素。
当我将处理程序的延迟设置为 10 毫秒并将 x 轴步长设置为 1 像素时,首先它会在 25 秒内绘制 1000 像素。锁定和解锁后它会下降 20 秒。
我知道我可能做错了。我的问题是,有没有办法使用 android 的原生画布绘图快速绘制图形?或者处理这样的应用程序的最佳方式是什么?