Android Canvas drawText not working

不问归期 提交于 2020-01-15 03:19:04

问题


I made a custom view using canvas's drawText method. Somehow none of the text is showing on any of the Jelly Bean devices. It works fine for ICS and below.

Does anyone know if anything has changed from API 15 to 16 for this method or any related methods?

Edit Code: (from the draw method where canvas is supplied as a parameter)

    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setStrokeWidth(3);
    paint.setColor(context.getResources().getColor(R.color.plot_background));
    canvas.drawRect(new Rect(0,0,getWidth(),getHeight()), paint);
    paint.setColor(color_text);
    paint.setTextSize(getScaled(18.5f));
    paint.setTextAlign(Align.CENTER);
    canvas.drawText(title, (graphwidth / 2) + horstart, border/2+15, paint);

I know the line is been executed and the coordinates are correct because the same code works on the older platforms.


回答1:


Thanks Eric. Figured out the error. I scale everything in the app base on canvas.getDensity(). getDensity() at the moment the draw function is ALWAYS 0 for jelly bean devices for some reason. But it does return the correct value for anything between 1.6 -> 4.0.3

I didn't post the code for that (which is my fault) is because I didn't suspect getDensity() to be the problem since it never did in the last two years while the app is in the market.

The workaround was to modify the getScaled function.

public float getScaled(Canvas canvas,float in){
    return in * ( canvas.getDensity()==0 ? 1 : canvas.getDensity()/ 160.0f);
} 

The documentation does say that DENSITY_NONE could be returned but I think what might have happened is that in Jelly Bean does the scaling for you since if I just multiply it by 1, it works as a charm on the two different density device that I just tested on.

(P.S. Can anyone familiar the internals of Android OS correct me if I am wrong or confirm it? )



来源:https://stackoverflow.com/questions/12120042/android-canvas-drawtext-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!