I have been looking for days on how to fix my issue and haven't really found an answer. So I apologize in advance if there already is a similar question.
My problem is simple. I want the user to input a name, and this name will be written on an image, in some kind of little box. (The image is then shared in an intent and everything, anyway...)
The image is a png in my drawable folder. So it should always have the same size in pixels on any kind of device.
I load the png on a bitmap, use canvas on that bitmap, create a paint and myPaint.setTextSize(100)
(setTextSize takes pixels so in this case it is 100 pixels) and then drawText on the canvas using that paint to have the same text size (in pixel) from whatever device is used.
The result is that writing "MyName" on one device fits perfectly, but on a smaller device would go out of the box, and on a larger device also.
I tried to use dp or sp, even if I knew it wouldn't change anything because we aren't talking about a layout, but a drawable png that has a fixed size.'
I have no issue with the position of the text or anything; only the size of it.
So anyway, I don't know where this change of textsize from one device to another comes from. Maybe I am not taking care of some kind of detail. I hope you guys can help me out.
Context context = getBaseContext();
Resources resources = context.getResources();
Bitmap card = BitmapFactory.decodeResource(resources, R.drawable.card);
android.graphics.Bitmap.Config bitmapConfig = card.getConfig();
if(bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
// Converting to mutable
card = card.copy(bitmapConfig, true);
Canvas canvas = new Canvas(card);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
// text color
paint.setColor(Color.WHITE);
paint.setFakeBoldText(true);
paint.setTextAlign(Paint.Align.CENTER);
// text size in pixels
paint.setTextSize(100);
// Name Position
float xName = (float) (0.744 * card.getWidth() );
float yName = (float) (0.680424 * (card.getHeight() - (paint.ascent()/2)));
String name = editName.getText().toString();
canvas.drawText(name, xName, yName, paint);