android - 如何减少TextView的行间距

标签 android fonts textview truetype

我正在尝试通过为 TextView.setLineSpacing() 设置一个负“添加”来减少 TextView 中的行距。它运作良好,除了底线被截断。

主要布局

<TextView
    android:id="@+id/text_view"
    android:padding="dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    tools:context=".MainActivity" />

主要 Activity :(注意

package com.font_test;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

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

        final Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/custom_fonts.ttf");
        final TextView tv = (TextView) findViewById(R.id.text_view);
        tv.setTypeface(typeface);
        tv.setTextSize(60);
        tv.setLineSpacing(-30f, 1f);  // *** -30 to reduce line spacing
        tv.setBackgroundColor(0x280000ff);
        tv.setText("gggkiiikkk" + "\n" + "gikgikgik" + "\n" + "kigkigkig");
    }
}

这会导致 View 底部被截断(请注意底部的“g”):

Reducing the line spacing cuts the 'g' at the bottom line

问题似乎与布局测量不正确有关。如果我将 TextView 设置为

 android:layout_height="fill_parent"

它确实正确呈现:

Using 'fill_parent' does not truncate the bottom line

知道如何解决吗?如果有帮助,我不介意有丑陋的解决方法。我还可以访问 FontForge,如果需要,我可以修改字体文件。

最佳答案

littleFluffyKittys 的回答很好,但如果行距是通过 xml 设置的,它在某些设备上不起作用

我通过将字体的原始高度与 textview 为一行计算的高度进行比较来计算所需的额外高度。 如果行高小于字体高度,差值增加一次。

这至少适用于可能更低的 API 10(只是没有测试过更低)

public class ReducedLineSpacingTextView extends TextView {

    public ReducedLineSpacingTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ReducedLineSpacingTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ReducedLineSpacingTextView(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int truncatedHeight = getPaint().getFontMetricsInt(null) - getLineHeight();
        if (truncatedHeight > 0) {
            setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight() + truncatedHeight);
        }
    }

}

关于android - 如何减少TextView的行间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11924280/

相关文章:

java - 将微调项目存储在字符串值中

Apache FOP : Displaying UTF-8 Characters in PDF (without embed? )

android - 如何以编程方式将 TextView 更改为 ImageView 并返回

android - 将 FILL_PARENT 宽度设置为位于 TableRow 内部的 TextView

android - 自定义 URL 方案 Android

android - 多个dex文件定义Lcom/amazonaws/AmazonWebServiceClient;

安卓回合制多人自定义邀请画面

css - 谷歌字体在 chrome 中被视为不安全的脚本

visual-studio - 在 Visual Studio SSIS 2012 中更改字体和颜色

android - 有没有办法在 ObjectAnimator 中为 textSize 指定 TypedValue?