Android快速精确的画布图形?

时间:2013-04-11 11:26:00

标签: android canvas graph handler ondraw

我正在开发一个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的原生画布绘制图形?或者处理这样的应用程序的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

多件事。

  • 每次都不要重新创建画布。这不是必需的。
  • 删除旧数据使用drawColor而不是drawRect。你需要先设置clipRect。
  • 不要使所有内容无效,只会使您更改的区域无效(即 - 相同的clipRect)
  • 禁用绘图缓存。基本上是因为您在自己的代码中处理缓存。请参阅评论以回答this question

答案 1 :(得分:0)

要添加到@ aragaer&#39; s answer

这里有一些有用的信息 - 对你来说最重要的部分是我建议你使用SurfaceView而不是普通的Canvas

我会阅读关于Android的游戏开发 - 你会在那里找到很多有用的高速绘图信息。

相关问题