---
title: "自定义view中获取字符串的宽度和高度"
author: "xubingok"
date: "2012-03-28T16:44:02Z"
tags: []
categories: ["移动开发"]
slug: "view"
draft: false
lastmod: "2012-03-28T16:44:02Z"
id: 1467197
url: "https://androidbin.iteye.com/blog/1467197"
---

方法1:

```java

Rect rect = new Rect();
Paint p = new Paint();
String str = "abcdefg";
p.getTextBounds(str, 0, str.length(), rect);//用一个矩形去"套"字符串,获得能完全套住字符串的最小矩形
float width = rect.width();//字符串的宽度
float height = rect.height();//字符串的高度

```


方法2:

```java

Paint p = new Paint();
String str = "abcdefg";
float width = p.measureText(str);//获得字符串的宽度

```