Android绘图视图非常慢

时间:2013-06-09 15:23:45

标签: android performance drawing

我从一个询问如何在Android中绘制的问题中得到了这个代码的答案,但是在使用它并在我的应用程序中测试时,我发现在绘制大件事物或许多路径时效率不高。问题来自onDraw内的代码,因为每次调用invalidate()时都会调用onDraw,其中包含一个循环,将所有paths再次抽取到canvas,并且通过添加更多路径,它变得非常慢。

这是班级:

public class DrawingView extends View implements OnTouchListener {
private Canvas m_Canvas;

private Path m_Path;

private Paint m_Paint;

ArrayList<Pair<Path, Paint>> paths = new ArrayList<Pair<Path, Paint>>();

ArrayList<Pair<Path, Paint>> undonePaths = new ArrayList<Pair<Path, Paint>>();

private float mX, mY;

private static final float TOUCH_TOLERANCE = 4;

public static boolean isEraserActive = false; 

private int color = Color.BLACK;
private int stroke = 6;

public DrawingView(Context context, AttributeSet attr) {
    super(context);
    setFocusable(true);
    setFocusableInTouchMode(true);

    setBackgroundColor(Color.WHITE);

    this.setOnTouchListener(this);

    onCanvasInitialization();
}

public void onCanvasInitialization() {
    m_Paint = new Paint();
    m_Paint.setAntiAlias(true);
    m_Paint.setDither(true);
    m_Paint.setColor(Color.parseColor("#000000")); 
    m_Paint.setStyle(Paint.Style.STROKE);
    m_Paint.setStrokeJoin(Paint.Join.ROUND);
    m_Paint.setStrokeCap(Paint.Cap.ROUND);
    m_Paint.setStrokeWidth(2);

    m_Canvas = new Canvas();

    m_Path = new Path();
    Paint newPaint = new Paint(m_Paint);
    paths.add(new Pair<Path, Paint>(m_Path, newPaint));
}

@Override
public void setBackground(Drawable background) {
    mBackground = background;
    super.setBackground(background);
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
}

public boolean onTouch(View arg0, MotionEvent event) {
    float x = event.getX();
    float y = event.getY();

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        touch_start(x, y);
        invalidate();
        break;
    case MotionEvent.ACTION_MOVE:
        touch_move(x, y);
        invalidate();
        break;
    case MotionEvent.ACTION_UP:
        touch_up();
        invalidate();
        break;
    }
    return true;
}

@Override
protected void onDraw(Canvas canvas) {
    for (Pair<Path, Paint> p : paths) {
        canvas.drawPath(p.first, p.second);
    }
}

private void touch_start(float x, float y) {

    if (isEraserActive) {
        m_Paint.setColor(Color.WHITE);
        m_Paint.setStrokeWidth(50);
        Paint newPaint = new Paint(m_Paint); // Clones the mPaint object
        paths.add(new Pair<Path, Paint>(m_Path, newPaint));
    } else { 
        m_Paint.setColor(color);
        m_Paint.setStrokeWidth(stroke);
        Paint newPaint = new Paint(m_Paint); // Clones the mPaint object
        paths.add(new Pair<Path, Paint>(m_Path, newPaint));
    }

    m_Path.reset();
    m_Path.moveTo(x, y);
    mX = x;
    mY = y;
}

private void touch_move(float x, float y) {
    float dx = Math.abs(x - mX);
    float dy = Math.abs(y - mY);
    if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
        m_Path.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
        mX = x;
        mY = y;
    }
}

private void touch_up() {
    m_Path.lineTo(mX, mY);

    // commit the path to our offscreen
    m_Canvas.drawPath(m_Path, m_Paint);

    // kill this so we don't double draw
    m_Path = new Path();
    Paint newPaint = new Paint(m_Paint); // Clones the mPaint object
    paths.add(new Pair<Path, Paint>(m_Path, newPaint));
}

public void onClickUndo() {
    if (!paths.isEmpty()) {//paths.size() > 0) {
        undonePaths.add(paths.remove(paths.size() - 1));
        undo = true;
        invalidate();
    }
}

public void onClickRedo() {
    if (!undonePaths.isEmpty()){//undonePaths.size() > 0) {
        paths.add(undonePaths.remove(undonePaths.size() - 1));
        undo = true;
        invalidate();
    }
}}

但是我再次在互联网上搜索以找到更好的绘图方式,所以我找到了以下内容:

1将以下内容添加到构造函数中:

mBitmapPaint = new Paint(Paint.DITHER_FLAG);

2使用以下代码覆盖onSizeChanged:

protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_4444);
    m_Canvas = new Canvas(mBitmap);
}

3把它放在onDraw:

protected void onDraw(Canvas canvas) {
    canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
    if (!paths.isEmpty())
        canvas.drawPath(paths.get(paths.size() - 1).first, paths.get(paths.size() - 1).second);
}

这种方法有效并且不会减慢视图速度,但这种方法的问题在于我无法使用撤消和重做功能。

我尝试了很多东西来进行撤销和第二种方法的重做,但是我无法做到。所以我在这里问的是三件事之一: 1.使用第二种方法进行撤消和重做的方法 2.另一种可以进行撤销和重做的方法 3.一个全新的类,包含已完成的所有内容,如开源库或其他内容。

如果可以,请帮忙。 感谢

编辑1

好的,所以我把它限制在此,然后我再做不了什么,我现在已经尝试了8个多小时。它一直工作直到撤消(你可以撤消任意数量的路径),然后当再次绘制所有剩余的路径消失时,我不知道是什么让它做到了。

@Override
protected void onDraw(Canvas canvas) {
    if (mBitmap != null)
        canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
    if (!paths.isEmpty() && !undo)
        canvas.drawPath(paths.get(paths.size() - 1).first, paths.get(paths.size() - 1).second);

    if (undo) {
        setBackground(mBackground);
        for (Pair<Path, Paint> p : paths)
            canvas.drawPath(p.first, p.second);

        mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_4444);
        m_Canvas = new Canvas(mBitmap);

        undo = false;
    }
}

基本上我所做的就是首先使用第一种方法(在调用撤销之前),然后如果点击撤消,undo设置为true,代码设置为if (undo)执行实际上是第一种方法(再次计算所有路径),然后我再次计算所有路径的结果到mBitmap,所以无论何时再次调用onDraw,它都会在此基础上绘制,但是那部分仍然需要工作,我希望有人可以帮助你。

3 个答案:

答案 0 :(得分:5)

处理这种情况的方法是使Bitmap具有视图的大小。在触摸事件上,绘制到位图的画布。在onDraw中,只需将位图绘制到0,0的画布上。对于撤消/重做,。你可以擦除位图并重新绘制所有路径。这需要花费更长的时间,但每次撤消/重做只发生一次。 如果用户通常执行一次撤消/重做。您只需退一步就可以通过另一个位图进行优化。

答案 1 :(得分:1)

好的,这就是我最后提出的问题,问题是我在撤消创建位图之前绘制了画布的路径,导致在撤消后丢失路径onDraw:

@Override
    protected void onDraw(Canvas canvas) {
        if (mBitmap != null)
            canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
        if (!paths.isEmpty()) {
            canvas.drawPath(paths.get(paths.size() - 1).first, paths.get(paths.size() - 1).second);
        }
    }

    public void onClickUndo() {
        if (paths.size() >= 2) {
            undonePaths.add(paths.remove(paths.size() - 2));
            mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            m_Canvas = new Canvas(mBitmap);

            for (Pair<Path, Paint> p : paths)
                m_Canvas.drawPath(p.first, p.second);
            invalidate();
        }
    }

    public void onClickRedo() {
        if (undonePaths.size() >= 2){
            paths.add(undonePaths.remove(undonePaths.size() - 2));
            mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            m_Canvas = new Canvas(mBitmap);

            for (Pair<Path, Paint> p : paths)
                m_Canvas.drawPath(p.first, p.second);
            invalidate();
        }
    }

一次又一次地绘制所有路径仍然存在但不在onDraw()中,这极大地提高了绘制的性能。 但是如果用户已经绘制了很多路径,那么用户可能会在onClickUndo()onClickRedo()中遇到一点延迟,因为路径会从头开始重新绘制,但每次点击只需要一次。

答案 2 :(得分:0)

我不确定这是否是撤消和重做的最佳方法。但是以下工作在我的设备上(三星galaxy s3)。 Draw似乎很快,撤消工作正常。我认为可以修改以下内容以进一步提高性能。

public class MainActivity extends Activity {
MyView mv;
LinearLayout ll;
private ArrayList<Path> undonePaths = new ArrayList<Path>();
private ArrayList<Path> paths = new ArrayList<Path>();
Button b;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         mv= new MyView(this);
            mv.setDrawingCacheEnabled(true);
            ll=  (LinearLayout) findViewById(R.id.ll);
            ll.addView(mv);
            b= (Button) findViewById(R.id.button1);
            b.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                     if (paths.size() > 0) {
                         undonePaths.add(paths
                                 .remove(paths.size()-2));
                         mv.invalidate();
                     }
                }

            });

    }
     public class MyView extends View implements OnTouchListener {

            private Canvas mCanvas;
            private Path mPath;
            private Paint mPaint;

            // private ArrayList<Path> undonePaths = new ArrayList<Path>();
            private float xleft, xright, xtop, xbottom;

            public MyView(Context context) {
                super(context);
                setFocusable(true);
                setFocusableInTouchMode(true);
                this.setOnTouchListener(this);
                mPaint = new Paint();
                mPaint.setAntiAlias(true);
                mPaint.setColor(Color.RED);
                mPaint.setStyle(Paint.Style.STROKE);
                mPaint.setStrokeJoin(Paint.Join.ROUND);
                mPaint.setStrokeCap(Paint.Cap.ROUND);
                mPaint.setStrokeWidth(6);
                mCanvas = new Canvas();
                mPath = new Path();
                paths.add(mPath);
            }

            @Override
            protected void onSizeChanged(int w, int h, int oldw, int oldh) {
                super.onSizeChanged(w, h, oldw, oldh);
            }

            @Override
            protected void onDraw(Canvas canvas) {
                for (Path p : paths) {
                    canvas.drawPath(p, mPaint);
                }
            }

            private float mX, mY;
            private static final float TOUCH_TOLERANCE = 0;

            private void touch_start(float x, float y) {
                mPath.reset();
                mPath.moveTo(x, y);
                mX = x;
                mY = y;
            }

            private void touch_move(float x, float y) {
                float dx = Math.abs(x - mX);
                float dy = Math.abs(y - mY);
                if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
                    mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
                    mX = x;
                    mY = y;
                }
            }

            private void touch_up() {
                mPath.lineTo(mX, mY);
                // commit the path to our offscreen
                mCanvas.drawPath(mPath, mPaint);
                // kill this so we don't double draw
                mPath = new Path();
                paths.add(mPath);
            }

            @Override
            public boolean onTouch(View arg0, MotionEvent event) {
                float x = event.getX();
                float y = event.getY();

                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:

                    touch_start(x, y);
                    invalidate();
                    break;
                case MotionEvent.ACTION_MOVE:
                    touch_move(x, y);
                    invalidate();
                    break;
                case MotionEvent.ACTION_UP:
                    touch_up();
                    invalidate();
                    break;
                }
                return true;
            }
        }
    }

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

     <LinearLayout
         android:id="@+id/ll"
         android:layout_width="match_parent"
         android:layout_height="fill_parent"
         android:layout_weight="1"
         android:orientation="vertical" >

 </LinearLayout>

 <Button
     android:id="@+id/button1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_gravity="center"
     android:text="Undo" />

</LinearLayout>