I have a button which is drawn using canvas onDraw
method. The button itself may will change size depending on device, but I want the text I'm drawing inside to remain consistent, even with different screen size or font size user may have set in settings. That is why I'm doing it in pixels.
@Override
public void onDraw(Canvas canvas) {
// 1. draw background
paint.setStyle(Paint.Style.FILL);
paint.setColor(colorBg);
canvas.drawRect(padding, padding, w-padding, h-padding, paint);
// 2. draw border
paint.setStyle(Paint.Style.STROKE);
paint.setColor(colorBorder);
canvas.drawRect(padding, padding, w-padding, h-padding, paint);
// 3. draw text
int fontSizeTextNew = canvas.getHeight() / 100 * 19;
int fontSizePaddingNew = canvas.getHeight() / 100 * 19;
textPaint.setTextSize(fontSizeTextNew);
textPaint.setShader(blackShader);
textPaint.setTypeface(Typeface.DEFAULT);
textPaint.getTextBounds(
prefTitle, // text
0, // start
prefTitle.length(), // end
rectangle // bounds
);
canvas.drawText(
prefTitle,
canvas.getWidth()/2,
Math.abs(rectangle.height()) + padding + fontSizePaddingNew,
textPaint
);
// 4. draw icon
int fontSizeIconNew = canvas.getHeight() / 100 * 55;
String str = prefIcon;
textPaint.setTypeface(awesomeFont);
textPaint.setTextSize(fontSizeIconNew);
textPaint.setShader(yellowShader);
// center for the text
// https://stackoverflow.com/questions/11120392/android-center-text-on-canvas
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
canvas.drawText(
str,
canvas.getWidth()/2,
Math.abs(yPos) + fontSizeIconPadding,
textPaint
);
}
This 19% looks nice right now but it will look different on variouse screens. What is your approach to this problem? how you would solvethis problem?
Button1 This is how it may look