Search code examples
androidandroid-canvasandroid-4.2-jelly-bean

DrawText only drawing one character of string on Jelly Bean 4.2


Okay, this is driving me nuts. I am using canvas to draw a gauge in my app. It also draws numbers on the hash marks and some horizontal text across the gauge. This all works fine in all versions of Android up to 4.2. In 4.2, it is only drawing one character (the middle character it seems) from the text it's supposed to write. For example, if I have text that reads 12345, it's only writing 3. If it's a two digit number, it only draws the first digit. I 'm seeing this behavior in the 4.2 emulator and on a Nexus 4 with 4.2.1. I read all about the hardware acceleration being turned on by default and that it causes problems with some Paint and Canvas features. I have inserted the code to turn off hardware acceleration for the drawText calls, but it doesn't help.

Here is my paint code:

titlePaint1 = new Paint();
titlePaint1.setColor(Color.WHITE);
titlePaint1.setAntiAlias(true);
titlePaint1.setTypeface(Typeface.DEFAULT_BOLD);
titlePaint1.setTextAlign(Paint.Align.CENTER);
titlePaint1.setTextSize(0.085f);

Here is the method called to draw the text:

@SuppressLint("NewApi")
private void drawTitle1(Canvas canvas) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        setLayerType(View.LAYER_TYPE_SOFTWARE, titlePaint1);

    canvas.drawText(title1, 0.5f, 0.72f, titlePaint1);
}

I pass it the canvas which is valid and the width and height are perfect. Everything else getting drawn on that canvas is displaying fine and there are three other calls to functions, like the one above, before it that draw the components of the gauge. It's just an issue with drawText. I know it has something to do with a change in 4.2 and I don't think this drawText issue has anything to do with hardware acceleration. I've only been able to find a few results on Google talking about Canvas issues with 4.2, but nothing has helped me to resolve my issue. Any ideas how I can resolve this and get the text to display properly?


Solution

  • Thank you to "Seraphim's host" for the answer to this in their post. For any others having this issue with 4.2.1, the answer is to include setLinearText(true) on your paint for the text. This method is showing as deprecated, but it's the only solution for the text to display properly.

    Here is the post with the answer: https://stackoverflow.com/a/13971632/1017328.