Java的Android的Canvas.drawText(...)的所有屏幕一样大 [英] Java Android Canvas.drawText(...) equally big in all screens
问题描述
我画的文字canvas.drawText(...)在我的项目,并测试它针对不同的设备。
I have drawn text with canvas.drawText(...)
in my project and tested it against with different devices.
然而,文本的大小而变化了很多,从画面到屏幕上。
However, the size of the text varies a lot from screen to screen.
我曾尝试与来乘以getResources()。getDisplayMetrics()。密度
但仍然是略微不一样的大小。
I have tried to multiply it with getResources().getDisplayMetrics().density
but they are still slightly not the same size.
有没有办法让文字拥有在不同设备上相同尺寸的?
Is there a way to get the text to have the same size on different devices?
推荐答案
您好,你可以看看这个帖子, HTTP :?//catchthecows.com/ p = 72 ,我认为它可以帮助你。
@覆盖
保护无效onSizeChanged(INT W,INT小时,INT oldw,诠释oldh){
super.onSizeChanged(W,H,oldw,oldh);
hi you can look at this post , http://catchthecows.com/?p=72, i think it helps to you. @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh);
// save view size
mViewWidth = w;
mViewHeight = h;
// first determine font point size
adjustTextSize();
// then determine width scaling
// this is done in two steps in case the
// point size change affects the width boundary
adjustTextScale();
}
void adjustTextSize() {
mTextPaint.setTextSize(100);
mTextPaint.setTextScaleX(1.0f);
Rect bounds = new Rect();
// ask the paint for the bounding rect if it were to draw this
// text
mTextPaint.getTextBounds(mText, 0, mText.length(), bounds);
// get the height that would have been produced
int h = bounds.bottom - bounds.top;
// make the text text up 70% of the height
float target = (float)mViewHeight*.7f;
// figure out what textSize setting would create that height
// of text
float size = ((target/h)*100f);
// and set it into the paint
mTextPaint.setTextSize(size);
}
void adjustTextScale() {
// do calculation with scale of 1.0 (no scale)
mTextPaint.setTextScaleX(1.0f);
Rect bounds = new Rect();
// ask the paint for the bounding rect if it were to draw this
// text.
mTextPaint.getTextBounds(mText, 0, mText.length(), bounds);
// determine the width
int w = bounds.right - bounds.left;
// calculate the baseline to use so that the
// entire text is visible including the descenders
int text_h = bounds.bottom-bounds.top;
mTextBaseline=bounds.bottom+((mViewHeight-text_h)/2);
// determine how much to scale the width to fit the view
float xscale = ((float) (mViewWidth-getPaddingLeft()-getPaddingRight())) / w;
// set the scale for the text paint
mTextPaint.setTextScaleX(xscale);
}
@Override
protected void onDraw(Canvas canvas) {
// let the ImageButton paint background as normal
super.onDraw(canvas);
// draw the text
// position is centered on width
// and the baseline is calculated to be positioned from the
// view bottom
canvas.drawText(mText, mViewWidth/2, mViewHeight-mTextBaseline, mTextPaint);
}
https://github.com/catchthecows/BigTextButton
这篇关于Java的Android的Canvas.drawText(...)的所有屏幕一样大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!