Smoothed very slow text animation on Android canvas, SUBPIXEL_TEXT_FLAG not working

I canโ€™t achieve smooth, very slow text animation in Canvas because Canvas.drawText does not want to draw โ€œbetween pixelsโ€. For example, given 4 consecutive frames, where I draw text with an offset of Y 0, 0.5, 1, 1.5, the canvas actually draws it at an offset of 0, 0, 1, 1, respectively, which causes the animation to be jerky. There's a flag called Paint.SUBPIXEL_TEXT_FLAG , which should support float precision.

I found a related thread in which Romain Guy said that this flag is not currently supported on Android: The value of some Paint constants in Android .

My question is: is there an existing workaround?

Note. Drawing text in another bitmap once, and then drawing this bitmap with float offsets, rather than drawing text, doesn't seem to work either.

+7
source share
1 answer

You can simulate this effect by drawing two texts side by side with alpha balancing (between 127 and 255) between two elements.

Suppose your text moves from bottom to top and your current vertical position is 10.28. You just need to draw one text at position 10 with an alpha close to 127, and another text at position 11 with an alpha close to 255.

Here is a bit (ugly: D) example:

 private void doDraw(Canvas canvas) { Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.BLACK); paint.setTextSize(20); canvas.drawRect(0, 0, getWidth(), getHeight(), paint); mY += 0.05f; paint.setColor(Color.RED); if (Math.floor(mY) == mY) { canvas.drawText("test", mX, mY, paint); } else { float mY1 = (float) Math.floor(mY); float mY2 = mY1 + 1; float delta = mY - mY1; paint.setAlpha((int) ((1 - delta) * 127) + 127); canvas.drawText("test", mX, mY1, paint); paint.setAlpha((int) ((delta) * 127) + 127); canvas.drawText("test", mX, mY2, paint); } } 
+3
source

All Articles