一、文本尺寸的测量
效果图:
实现步骤:
activity_main.xml 布局中定义控件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="40dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:gravity="center"
android:text="字体大小:20sp"
android:textColor="@color/black"
android:textSize="17sp"
/>
</RelativeLayout>
<TextView
android:id="@+id/tvShowWidthHeight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="@color/black"
android:textSize="20sp" />
<TextView
android:id="@+id/tvText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="每逢佳节倍思亲"
android:textColor="@color/black"
android:background="@color/red"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>
MainActivity 中测量
/**
* 文本尺寸 测量
*/
public class MainActivity extends Activity {
// 显示文字的宽高
private TextView tvShowWidthHeight;
// 显示文字
private TextView tvText;
// 设置字体大小是 20sp
private int textSize = 20;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化控件
tvShowWidthHeight = findViewById(R.id.tvShowWidthHeight);
tvText = findViewById(R.id.tvText);
// 设置文字的大小
tvText.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
// 拿到字符串
String text = tvText.getText().toString().trim();
// 计算获取指定文本的宽度
int width = (int) MeasureUtil.getTextWidth(text, textSize);
// 计算获取指定文本的高度
int height = (int) MeasureUtil.getTextHeight(text, textSize);
// 显示文本的宽高
tvShowWidthHeight.setText("文字的宽度是"+width+";"+"文字的高度是"+height);
}
}
MeasureUtil 工具类中,测量代码:
/**
* 获取指定文本的宽度(其实就是长度)
* text 字符串
* textSize 文字的大小
*
*/
public static float getTextWidth(String text, float textSize) {
if (TextUtils.isEmpty(text)) {
return 0;
}
Paint paint = new Paint(); // 创建一个画笔对象
paint.setTextSize(textSize); // 设置画笔的文本大小
return paint.measureText(text); // 利用画笔丈量指定文本的宽度
}
/**
* 获取指定文本的高度
* text 字符串
* textSize 文字的大小
*/
public static float getTextHeight(String text, float textSize) {
Paint paint = new Paint(); // 创建一个画笔对象
paint.setTextSize(textSize); // 设置画笔的文本大小
Paint.FontMetrics fm = paint.getFontMetrics(); // 获取画笔默认字体的度量衡
return fm.descent - fm.ascent; // 返回文本自身的高度
//return fm.bottom - fm.top + fm.leading; // 返回文本所在行的行高
}
二、图片尺寸的测量
测量高度,直接使用 getWidth()
测量宽度,直接使用 getHeight()
源码下载:
TestCustom ---- app0
https://download.csdn.net/download/zhaihaohao1/11224806