我需要编写自定义视图,它会从右到左平滑地滚动多个文本。
好吧,我已经写过了,但是滚动看起来不够顺畅。这是代码:
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);
}
}
}
它并不是很复杂,但是滚动看起来并不平滑,时不时会产生不安。我在绘图期间没有进行任何分配。
任何想法如何改善这一点?
答案 0 :(得分: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();
}
}
}
答案 1 :(得分:0)
通过使用SurfaceView而不是View,我获得了更好的速度。