0

我需要编写自定义视图,它将从右到左平滑滚动几个文本。

好吧,我已经写过了,但是滚动看起来不够流畅。这是代码:

private Runnable tick = new Runnable() {
    @Override
    public void run() {
        anim();
        invalidate();
        handler.postDelayed(this, 10);
    }
};

private void anim()
{
    long time = System.currentTimeMillis();
    long dTime = time - animStartTime;
    animStartTime = time;

    offsetX-=(float)(dTime*ANIM_SPEED);
}

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



    if(rates!=null)
    {
        for(int i=0; i<rates.length; i++)
        {
            Rate r = rates[i];
            float x = ((i*rateWidth) + offsetX + r.offsetX);
            float y = 120;

            if(x>w)
            {
                continue;
            }
            else if(x+rateWidth<0)
            {
                r.offsetX += rates.length*rateWidth;
                continue;
            }

            canvas.drawText(r.currency, x, y, paintBlack);

        }
    }

}

它不是很复杂,但是滚动看起来一点也不流畅,并且不时抖动。在绘图期间我没有进行任何分配。

有什么想法可以改进吗?

4

2 回答 2

0

我只是在我的设备上测试我的代码,你可以试试。在 OnDraw 中使用您的代码而不是我的代码。

public class MoveText extends View {

private Scroller mScroller;

private Paint mPaint;

private int x;

public MoveText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

public MoveText(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public MoveText(Context context) {
    super(context);
    init();
}

private void init() {
    mScroller = new Scroller(getContext(), new LinearInterpolator());
    mPaint = new Paint();
    mPaint.setColor(Color.BLACK);
    mPaint.setTextSize(30f);
}

@Override
public void computeScroll() {
    super.computeScroll();
    // loop invalidate until the scroller animation is finish.
    if (mScroller.computeScrollOffset()) {
        x = mScroller.getCurrX();
        invalidate();
    }
}

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

    // please use your code instead of mine below.
    canvas.drawText("scrolling text", x, mPaint.getTextSize(), mPaint);
}

/**
 * start text translate animation.
 */
public void startScroll() {
    if (mScroller.isFinished()) {
        int width = getWidth();
        mScroller.startScroll(0, 0, width, 0, 10000);
        postInvalidate();
    }

}
}
于 2013-08-17T11:27:27.287 回答
0

通过使用 SurfaceView 而不是 View,我获得了更好的速度。

于 2013-08-21T06:30:50.637 回答