首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何基于android displayMetrics缩放字体大小?

如何基于android displayMetrics缩放字体大小?
EN

Stack Overflow用户
提问于 2019-05-27 15:08:37
回答 2查看 1.1K关注 0票数 1

我正在编写一个应用程序,在安卓系统中显示一个简单的数字时钟,我需要缩放TextView的字体大小,这样它就能尽可能地填充屏幕。我发现了一种使用displayMetrics来缩放文本大小的非常简单的方法,但是它在某些设备上不能正常工作。我想要达到的目标如下:

我只会在景观模式下工作,我希望它能在我的旧智能手机和平板电脑上运行,就像在新设备上一样。所以我有各种各样的屏幕类型可供选择。

若要缩放字体,请执行以下操作

代码语言:javascript
运行
AI代码解释
复制
    ...
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_clock);

    // Get screen size and calculate text size needed to fit
    // TODO: doesn't work well on some devices
    TextView tvScreenSize = findViewById(R.id.tvScreenSize);
    DisplayMetrics displayMetrics = new DisplayMetrics(); // From: https://stackoverflow.com/questions/4743116/get-screen-width-and-height
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    // The screen height and width are recalculated automatically by Android when the screen is redrawn on a rotation
    height = displayMetrics.heightPixels;
    width = displayMetrics.widthPixels;
    textSP = width / 12; // Empirical value
    String hString = Integer.toString(height);
    String wString = Integer.toString(width);
    tvScreenSize.setText("h: " + hString + "  w:" + wString);

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            // Display time of day
            Date curDate = new Date();
            TextView tvTime = findViewById(R.id.clockView);
            String timeStr = format.format(curDate);

            tvTime.setText(timeStr);
            tvTime.setScaleY(1.5f);
            tvTime.setWidth(width * 8 / 10); // Make it fill 80% of the screen
            tvTime.setHeight(height * 8 / 10);
            tvTime.setTextSize(textSP);
            ...

这张支票的行文是:

代码语言:javascript
运行
AI代码解释
复制
textSP = width / 12; // Empirical value

对于某些屏幕,6的值很好。对于其他屏幕,这创建了一个字体如此大,只有一小部分是可见的。将此值更改为12就可以了。

似乎我遗漏了一些与屏幕密度有关的东西,但又是什么呢?

谢谢!

最终结果:对于任何想要缩放像我这样的文本的人,下面是ismail输入后的最后代码:

activity_main.xml文件:

代码语言:javascript
运行
AI代码解释
复制
?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@+id/tvClockFace"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="6dp"
    android:text="12:34"
    android:textColor="@android:color/holo_red_dark"
    android:textSize="30sp"
    android:textStyle="bold"
    android:typeface="monospace"
    app:fontFamily="monospace"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/tvScreenSize"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:text="H:... W:..."
    android:textSize="14sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>

MainActivity.java:

代码语言:javascript
运行
AI代码解释
复制
package com.schalkx.testautosizeclockdisplay;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.Display;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Scale the textsize automatically
    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics outMetrics = new DisplayMetrics ();
    display.getMetrics(outMetrics);

    float density  = getResources().getDisplayMetrics().density;
    float dpHeight = outMetrics.heightPixels / density;
    float dpWidth  = outMetrics.widthPixels / density;

    // Convert height and width to integer values
    float fTextSize = dpWidth/4; // Trial and error
    // int iTextSize = Math.round(fTextSize);
    int scrHeight = Math.round(dpHeight);
    int scrWidth = Math.round(dpWidth);

    // Display de height and width on screen (for reference)
    String wString = Integer.toString(scrWidth); // In case you need the width
    String hString = Integer.toString(scrHeight); // Same for height
    TextView tvScreenSize = findViewById(R.id.tvScreenSize);
    tvScreenSize.setText("h: " + hString + "  w:" + wString);

    // Scale the font of the clock face
    TextView tvClockFace = findViewById(R.id.tvClockFace);
    // tvClockFace.setHeight(50);
    // tvClockFace.setWidth(100);
    tvClockFace.setTextSize(fTextSize);
    tvClockFace.setScaleY(1.5f);
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-27 17:01:15

为了获得更好的显示体验,您应该使用dp而不是px,这里介绍了如何获得dp大小:

代码语言:javascript
运行
AI代码解释
复制
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);

float density  = getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth  = outMetrics.widthPixels / density;

因此,现在可以相应地将文本大小设置为屏幕dpHeightdpWidht

票数 1
EN

Stack Overflow用户

发布于 2019-05-27 15:41:54

不要在代码中使用像素值。将像素转换为独立于设备的像素(Dp)

代码语言:javascript
运行
AI代码解释
复制
public static float convertPixelsToDp(float px, Context context){
    return px / ((float) context.getResources().getDisplayMetrics().densityDpi/ 
         DisplayMetrics.DENSITY_DEFAULT);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56333296

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档