如何在画布上优化绘图文本

时间:2012-12-29 22:10:53

标签: android android-canvas

我有3个圆圈的窗口,它们同时旋转。一切都很好,直到向圆圈添加文本,然后旋转开始滞后。

main window

如何在画布上优化绘图? 这是我的代码:

@Override
protected void onDraw(final Canvas canvas) {
    if (mPaint == null) {
        mPaint = new Paint();
        mPaint.setTextSize(20f);
    }       
    drawUpperCircle(canvas);
    drawBottomCircle(canvas);
    drawMainCircle(canvas);

    try {
        Thread.sleep(1, 1);
        invalidate();
        mRotation += 0.9;
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    super.onDraw(canvas);
}
   private void drawUpperCircle(Canvas canvas) {
    canvas.save();
    canvas.rotate(mRotation, 0, mUpperCircleCentr);
    mPaint.setColor(Color.CYAN);
    canvas.drawCircle(0, mUpperCircleCentr, mUpperCirclRadius, mPaint);
    mPaint.setColor(Color.BLACK);
    for (int i = 0; i < SEG_COUNT; i++) {
        canvas.rotate(SEG_IN_GRAD, 0, mUpperCircleCentr);
        canvas.drawLine(0, mUpperCircleCentr, mUpperCirclRadius, mUpperCircleCentr, mPaint);
        //          canvas.drawText("my text" + String.valueOf(i), mUpperCirclRadius * 2 / 3, mUpperCircleCentr - 4, mPaint);
    }
    canvas.restore();
}

private void drawBottomCircle(Canvas canvas) {
    canvas.save();
    canvas.rotate(mRotation, 0, mBottomCircleCentr);
    mPaint.setColor(Color.RED);
    canvas.drawCircle(0, mBottomCircleCentr, mBottomCirclRadius, mPaint);
    mPaint.setColor(Color.BLACK);
    for (int i = 0; i < SEG_COUNT; i++) {
        canvas.rotate(SEG_IN_GRAD, 0, mBottomCircleCentr);
        canvas.drawLine(0, mBottomCircleCentr, mBottomCirclRadius, mBottomCircleCentr, mPaint);
        //          canvas.drawText("my text" + String.valueOf(i), mBottomCirclRadius * 2 / 3, mBottomCircleCentr - 4, mPaint);
    }
    canvas.restore();
}

private void drawMainCircle(Canvas canvas) {
    canvas.save();
    canvas.rotate(mRotation, 0, mMainCircleCentr);
    mPaint.setColor(Color.argb(100, 100, 100, 100));
    canvas.drawCircle(0, mMainCircleCentr, mMainCirclRadius, mPaint);
    mPaint.setColor(Color.BLACK);
    for (int i = 0; i < SEG_COUNT; i++) {
        canvas.rotate(SEG_IN_GRAD, 0, mMainCircleCentr);
        canvas.drawLine(0, mMainCircleCentr, mMainCirclRadius, mMainCircleCentr, mPaint);
        canvas.drawText("my text" + String.valueOf(i), mMainCirclRadius * 2 / 3, mMainCircleCentr - 4, mPaint);
    }
    canvas.restore();
}

修改的 为了提高性能并从UI线程中删除绘图,我使用了SurfaceView的双缓冲并实现了@Morgans优化。这就是它实现的方式。

DrawView.java

public class DrawView extends SurfaceView implements SurfaceHolder.Callback {

...............................................................

public DrawView(Context context, AttributeSet attrs) {
    super(context, attrs);
    getHolder().addCallback(this);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    float currentX = event.getX();
    float currentY = event.getY();
    float deltaX, deltaY;
    switch (event.getAction()) {
    case MotionEvent.ACTION_MOVE:
        // Modify rotational angles according to movement
        deltaX = currentX - previousX;
        deltaY = currentY - previousY;
        mDrawThread.mRotation += deltaY * 180 / getHeight();
    }
    // Save current x, y
    previousX = currentX;
    previousY = currentY;
    return true; // Event handled
}

@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {

}

@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
    mDrawThread = new DrawThread(getHolder(), this);
    mDrawThread.setRunning(true);
    mDrawThread.start();
}

@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
    boolean retry = true;
    mDrawThread.setRunning(false);
    while (retry) {
        try {
            mDrawThread.join();
            retry = false;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 }

主要工作在 DrawThread.java

中完成
public class DrawThread extends Thread {

private ArrayList<Path> mMainCirclePaths = new ArrayList<Path>(SEG_COUNT);
private ArrayList<Path> mUpperCirclePaths = new ArrayList<Path>(SEG_COUNT);
private ArrayList<Path> mCenterCirclePaths = new ArrayList<Path>(SEG_COUNT);
private ArrayList<Path> mBottomCirclePaths = new ArrayList<Path>(SEG_COUNT);

private boolean mRun = false;
private SurfaceHolder mSurfaceHolder;
private DrawView mDrawView;
private Paint mPaint;

private CirclesModel mCirclesModel;
public float mRotation = 0;

public DrawThread(SurfaceHolder surfaceHolder, DrawView drawView) {
    mSurfaceHolder = surfaceHolder;
    mDrawView = drawView;
    mCirclesModel = new CirclesModel(mDrawView.getHeight());
    mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mPaint.setTextSize(18f);
    initPaths();
}

public void setRunning(boolean b) {
    mRun = b;
}

@Override
public void run() {
    while (mRun) {
        Canvas canvas = null;
        try {
            canvas = mSurfaceHolder.lockCanvas(null);
            synchronized (mSurfaceHolder) {
                drawMainCircle(canvas);
                mPaint.setColor(Color.WHITE);
                canvas.drawCircle(mCirclesModel.mMainCircleCentr[CirclesModel.X], mCirclesModel.mMainCircleCentr[CirclesModel.Y],
                        mCirclesModel.mSmallCirclesRadius, mPaint);
                drawCenterCircle(canvas);
                drawUpperCircle(canvas);
                drawBottomCircle(canvas);
                //mRotation += 0.5f;

            }
        } finally {
            if (canvas != null) {
                mSurfaceHolder.unlockCanvasAndPost(canvas);
            }
        }
    }
}

private void drawMainCircle(Canvas canvas) {
    canvas.save();
    canvas.rotate(mRotation, mCirclesModel.mMainCircleCentr[CirclesModel.X], mCirclesModel.mMainCircleCentr[CirclesModel.Y]);
    float rot = mRotation;
    mPaint.setColor(Color.LTGRAY/* argb(100, 255, 255, 255) */);
    canvas.drawCircle(mCirclesModel.mMainCircleCentr[CirclesModel.X], mCirclesModel.mMainCircleCentr[CirclesModel.Y],
            mCirclesModel.mBigCirclesRadius, mPaint);
    mPaint.setColor(Color.BLACK);
    for (int i = 0; i < SEG_COUNT; i++) {
        canvas.rotate(SEG_IN_GRAD, mCirclesModel.mMainCircleCentr[CirclesModel.X], mCirclesModel.mMainCircleCentr[CirclesModel.Y]);
        rot += SEG_IN_GRAD;
        float absRot = Math.abs(rot % 360);
        if (absRot > mCirclesModel.mMainCircleSegment[0] && absRot < mCirclesModel.mMainCircleSegment[1]) {
            continue;
        }
        canvas.drawLine(mCirclesModel.mMainCircleCentr[CirclesModel.X], mCirclesModel.mMainCircleCentr[CirclesModel.Y],
                mCirclesModel.mBigCirclesRadius, mCirclesModel.mMainCircleCentr[CirclesModel.Y], mPaint);
        canvas.drawPath(mMainCirclePaths.get(i), mPaint);
        // canvas.drawText("my text" + String.valueOf(i),
        // mMainCirclRadius * 2 / 3, mMainCircleCentr - 4, mPaint);
    }
    canvas.restore();
}
   .................................................................
}

双缓冲在两行代码中实现

canvas = mSurfaceHolder.lockCanvas(null);这里我从表面视图画布中取出,我将在其中绘制下一帧。

mSurfaceHolder.unlockCanvasAndPost(canvas);这里我将SurfaceView上的当前图像与新的canwas重叠,这是图像变化的时刻。请注意,如果您有透明元素,则前一个图像仍然可见,图像不会被替换,但会重叠。

2 个答案:

答案 0 :(得分:8)

以下是包含一些优化的代码版本。

首先,我尝试不绘制当前屏幕外的行和文本。我这样做是通过跟踪旋转角度,并跳过图纸以获得90到270度之间的净旋转。在我的2.3模拟器上,整体性能提高了25%。

其次,我通过为每个需要绘制的字符串初始化一个ArrayList<Path>的数组(“Path”来“缓存”我要绘制的字符串。我在一次初始化mPaint的同一个地方这样做。然后我使用canvas.drawPath(...)绘制字符串。在我的2.3模拟器上,这个性能提高了33%。净效应是转速的两倍左右。此外,它阻止了文字“摆动”。

其他几点说明:

我删除了Thread.sleep(1,1)。不确定你到底想要完成什么。

我将旋转增量从0.9更改为1.0。不知道你为什么使用0.9。请注意,如果您更改为后退,我的“旋转10度所需的日志时间”将无法正常工作,因为mRotation % 10可能很少为0。

在4.1模拟器上,旋转速度通常比我的2.3模拟器快得多(约4倍)。而4.1设备的速度更快。

public class AnimView extends View {
Paint mPaint;
ArrayList<Path> mTextPaths;

float mRotation = 0f;

float mUpperCircleCentr = 150f;
float mUpperCirclRadius = 150f;

private static final int SEG_COUNT = 60;
private static final float SEG_IN_GRAD = 360.0f / SEG_COUNT;

float mBottomCircleCentr = 450f;
float mBottomCirclRadius = 150f;

float mMainCircleCentr = 300f;
float mMainCirclRadius = 300f;

long mLastMillis = 0L;

// ctors removed

@Override
protected void onDraw(final Canvas canvas) {
    super.onDraw(canvas);

    if (mPaint == null) {
        mPaint = new Paint();
        mPaint.setTextSize(20f);

        // init text paths
        mTextPaths = new ArrayList<Path>(SEG_COUNT);
        for (int i = 0; i < SEG_COUNT; i++) {
            Path path = new Path();
            String s = "my text" + String.valueOf(i);
            mPaint.getTextPath(s, 0, s.length(), mMainCirclRadius * 2 / 3, mMainCircleCentr - 4, path);
            path.close(); // not required on 2.2/2.3 devices
            mTextPaths.add(path);
        }
    }
    if (mLastMillis == 0L) {
        mLastMillis = System.currentTimeMillis();
    }

    drawUpperCircle(canvas);
    drawBottomCircle(canvas);
    drawMainCircle(canvas);

    invalidate();

    if (((int) mRotation) % 10 == 0) {
        long millis = System.currentTimeMillis();
        Log.w("AnimateCanvas", "OnDraw called with mRotation == " + mRotation);
        Log.w("AnimateCanvas", "Last 10 degrees took millis: " + (millis - mLastMillis));
        mLastMillis = millis;
    }
}

private void drawUpperCircle(Canvas canvas) {
    canvas.save();
    canvas.rotate(mRotation, 0, mUpperCircleCentr);
    float rot = mRotation;
    mPaint.setColor(Color.CYAN);
    canvas.drawCircle(0, mUpperCircleCentr, mUpperCirclRadius, mPaint);
    mPaint.setColor(Color.BLACK);
    for (int i = 0; i < SEG_COUNT; i++) {
        canvas.rotate(SEG_IN_GRAD, 0, mUpperCircleCentr);
        rot += SEG_IN_GRAD;
        if (rot % 360 > 90 && rot % 360 < 270)
            continue;
        canvas.drawLine(0, mUpperCircleCentr, mUpperCirclRadius, mUpperCircleCentr, mPaint);
    }
    canvas.restore();
}

private void drawBottomCircle(Canvas canvas) {
    canvas.save();
    canvas.rotate(mRotation, 0, mBottomCircleCentr);
    float rot = mRotation;
    mPaint.setColor(Color.RED);
    canvas.drawCircle(0, mBottomCircleCentr, mBottomCirclRadius, mPaint);
    mPaint.setColor(Color.BLACK);
    for (int i = 0; i < SEG_COUNT; i++) {
        canvas.rotate(SEG_IN_GRAD, 0, mBottomCircleCentr);
        rot += SEG_IN_GRAD;
        if (rot % 360 > 90 && rot % 360 < 270)
            continue;
        canvas.drawLine(0, mBottomCircleCentr, mBottomCirclRadius, mBottomCircleCentr, mPaint);
    }
    canvas.restore();
}

private void drawMainCircle(Canvas canvas) {
    canvas.save();

    canvas.rotate(mRotation, 0, mMainCircleCentr);
    float rot = mRotation;
    mPaint.setColor(Color.argb(100, 100, 100, 100));
    canvas.drawCircle(0, mMainCircleCentr, mMainCirclRadius, mPaint);
    mPaint.setColor(Color.BLACK);
    for (int i = 0; i < SEG_COUNT; i++) {
        canvas.rotate(SEG_IN_GRAD, 0, mMainCircleCentr);
        rot += SEG_IN_GRAD;
        if (rot % 360 > 90 && rot % 360 < 270)
            continue;
        canvas.drawLine(0, mMainCircleCentr, mMainCirclRadius, mMainCircleCentr, mPaint);
        canvas.drawPath(mTextPaths.get(i), mPaint);
        // canvas.drawText("my text" + String.valueOf(i), mMainCirclRadius * 2 / 3, mMainCircleCentr - 4, mPaint);
    }
    canvas.restore();
}
}

答案 1 :(得分:3)

您的代码非常简单。您可以通过使用较少的循环来优化它,例如将所有内容绘制在一起或组合变量,但这很快就会变得混乱。

我建议你保持你的绘图代码或多或少相等。你实际上并没有做最糟糕的事情:实例化对象,而且它很容易维护。

但你可以尝试使用双缓冲区:在ram中的缓冲区中绘制并在屏幕上一次性翻转缓冲区。这通常表现得很好,以获得恒定的动画节奏。使用锁定和解锁画布:Double buffering in Java on Android with canvas and surfaceview