Android将TextView文本大小设置为在所有屏幕大小上都相同 [英] Android set TextView text size to look the same on all screen sizes

查看:425
本文介绍了Android将TextView文本大小设置为在所有屏幕大小上都相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方形LinearLayout,其中包含其他一些LinearLayouts,其中包含ImageViewsTextViews.用户更改布局内容后,我将布局内容另存为png文件.所有图像和文本都使用常规的gravity和layout_gravity值进行排列.这是一个小样本:

I have a square LinearLayout containing a few other LinearLayouts with ImageViews and TextViews inside. I am saving the layout content as png file after the user changes it. All the Images and Texts are being arranged using the general gravity and layout_gravity values. Here is a small sample:

这是我的问题:我希望SAMPLE TEXT在所有屏幕尺寸上看起来都完全相同,无论是480p的电话还是1200p的平板电脑.最初,我认为在SP中设置文本大小就足够了,但事实并非如此,因为随着屏幕分辨率变大,文本变小.

Here is my problem: I want the SAMPLE TEXT to look exactly the same size on all screen sizes, being a phone of 480p or a tablet of 1200p. Initially I thought that setting the text size in SP will be enought but it is not, because as screen resolution gets bigger, the text gets smaller.

所以我的问题是,如何以编程方式设置文本大小,使其看起来完全相同,而与屏幕宽度无关.如您所见,父布局将始终是正方形.

So my question is, how can I programatically set the text size so it will look exactly of the same size, independent of screen width. As you can see the parent layout will always be a square.

我尝试以编程方式设置SP或使用比例因子.

I tried programatically setting SP or using a scale factor.

float scale = 0;

if (screenWidth == 720) {
        scale = 1;
} else {
        scale = (720 - screenWidth) * 100.2f / screenWidth;
}

float defaultSizeFor720 = 35f;

textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, defaultSizeFor720 * scale);

它不起作用.随着屏幕变大,文本变小,但不像仅使用SP时那样小,但仍然如此.我也尝试了其他问题的大多数答案,但仍然没有用. 有什么想法吗?

It does not work. as screen gets bigger, text gets smaller, not as small as when only using SP alone, but still. I also tried most of the answers from other questions but still did not work. Any ideas?

推荐答案

我发现的唯一可靠的方法是:

The only reliable method I found was:

  • 具有默认屏幕尺寸的文本高度
  • 根据当前屏幕尺寸缩放此文本高度
  • 在文本大小中找到最佳匹配以适合所需的高度

  • have a text height for a default screen size
  • scale this text height based on current screen size
  • find the best match in text size to fit the needed height

float DEFAULT_SCREEN_WIDTH = 720f;

float TEXT_HEIGHT = 50f;
float sizeLine1 = (screenWidth * TEXT_HEIGHT) / DEFAULT_SCREEN_WIDTH;
Rect bounds = new Rect();
int textSize = 1;
while (bounds.height() < sizeLine1) {
    textSize++;
    txtLine1.getPaint().setTextSize(textSize);
    txtLine1.getPaint().getTextBounds("test", 0, "test".length(), bounds);
}

可能不雅致或高效,但是可以接受并且确实有效.平板电脑1200p和480p手机之间存在细微的差异,但就我而言,这是可以的.

Might not be elegant or efficient, but it is acceptable, and does work. There are minor differences between tablet 1200p and 480p phones, but these are OK in my case.

这篇关于Android将TextView文本大小设置为在所有屏幕大小上都相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆