THIS IS NOT ABOUT AntiAlias, Please read the question before answering thank you.
ADDING BOUNTY TO--> android convert text width (in pixels) to percent of screen width/height
Quality info --> https://stackoverflow.com/a/1016941/1815624
I am getting inconsistent results when trying to draw text on a canvas. Please help, thank you.
I want the text to consume the same amount of scaled space on all devices
I do not care about ANTI_ALIAS and have added the paint.setFlags(Paint.ANTI_ALIAS_FLAG);
but the problem is the same...
On 1 screen the text consumes half the width, on another only a 1/3 and even one that uses the full width.
I want them all to use equal amounts of screen real estate.
For Example
1600X900 7inch tablet Kitkat physical:
1600x900 20in Lollipop emulated
These have been created using the guide at http://www.gkproggy.com/2013/01/draw-text-on-canvas-with-font-size.html
where as that tutorial is showing consistent results
To be thorough here is the source:
public class MainActivity extends Activity
{
Paint paint;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
paint = new Paint();
View test = new TestView(this);
setContentView(test);
}
public class TestView extends View
{
public TestView(Context context)
{
super(context);
setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
public float pixelsToSp(Context context, float px) {
float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
return px/scaledDensity;
}
public float spToPixels(float sp) {
Context context = getContext();
float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
return scaledDensity*sp;
}
@Override
protected void onDraw(Canvas canvas)
{
int size = getResources().getDimensionPixelSize(R.dimen.sp20);
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics());
Log.v("intSize", Integer.toString(size));
Log.v("intSize", Integer.toString(px));
Log.v("intSize", Float.toString(spToPixels(20f)));
if(true) {
Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/Ultra.ttf");
paint.setTypeface(myTypeface);
}
paint.setColor(Color.BLACK);
paint.setTextSize(size);
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
canvas.drawText("HELLOOOOOOOOOOOOOO!", 0, size, paint);
super.onDraw(canvas);
}
}
}
I have tried suggestion from https://stackoverflow.com/a/5369766/1815624
Looking into this
https://stackoverflow.com/a/21895626/1815624
https://stackoverflow.com/a/14753968/1815624
https://stackoverflow.com/a/21895626/1815624 <-- trying now
Resources used:
https://stackoverflow.com/a/4847027/1815624
https://stackoverflow.com/a/21895626/1815624
Got to get screen width, some reference of text size to screen ratio, and calculate. so the results are:
and
notice the second HELLOOOOOOOOOOOOOOOOO!
please note if you not extending Activity use
instead of