获取文本在 TextView 中的位置
get position of the text inside a TextView
假设我在 TextView
中有以下文本 'ADD TEST' ,如下所示
如您所见,TextView
中的文本与 TextView
的宽度和高度不同。
我想要的是获取 TextView
中文本的 x,y 位置
Y值
您可以使用 textView.getTextSize()
或 textView.getPaint().getTextSize()
获取实际使用的文本大小(以像素为单位)(如 Float
)。
接下来,我们需要文本视图的总高度,我们可以这样找到:
textView.measure(0, 0); // We must call this to let it calculate the heights
int height = textView.getMeasuredHeight();
不过,我们需要的最终尺寸也可以有小数。因此,让我们将其设为浮点数以提高精度:
float totalHeight = (float) height;
现在我们知道了这些值,我们可以计算视图内文本的 y 值:
// The spacing between the views is `totalHeight - textSize`
// We have a spacing at the top and the bottom, so we divide it by 2
float yValue = (totalHeight - textSize) / 2
X值
此外,xValue只是使用时文本视图本身的x值
android:includeFontPadding="false"
.
看看几个 Paint
方法:getTextBounds()
and measureText
。我们可以使用这些来确定文本在 TextView
内的偏移量。一旦确定了 TextView
中的偏移量,我们就可以将其添加到 TextView
本身的位置以确定文本的屏幕坐标(如果需要的话)。
我还发现文章 "Android 101: Typography" 有助于理解排版的一些复杂性。
以下示例查找三个 TextViews
以内的文本边界,并在文本周围绘制一个矩形。该矩形包含 TextView
.
中文本的 (x, y) 坐标
activity_main.xml
用于演示的简单布局。
<android.support.constraint.ConstraintLayout
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:background="@android:color/holo_blue_light"
android:padding="24dp"
android:text="Hello World"
android:textColor="@android:color/black"
android:textSize="50sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:background="@android:color/holo_blue_light"
android:padding="24dp"
android:text="Hello Worldly"
android:textColor="@android:color/black"
android:textSize="50sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/textView1" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:background="@android:color/holo_blue_light"
android:padding="24dp"
android:text="aaaaaaaaaa"
android:textColor="@android:color/black"
android:textSize="50sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/textView2" />
</android.support.constraint.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawTextBounds((TextView) findViewById(R.id.textView1));
drawTextBounds((TextView) findViewById(R.id.textView2));
drawTextBounds((TextView) findViewById(R.id.textView3));
}
private void drawTextBounds(TextView textView) {
// Force measure of text pre-layout.
textView.measure(0, 0);
String s = (String) textView.getText();
// bounds will store the rectangle that will circumscribe the text.
Rect bounds = new Rect();
Paint textPaint = textView.getPaint();
// Get the bounds for the text. Top and bottom are measured from the baseline. Left
// and right are measured from 0.
textPaint.getTextBounds(s, 0, s.length(), bounds);
int baseline = textView.getBaseline();
bounds.top = baseline + bounds.top;
bounds.bottom = baseline + bounds.bottom;
int startPadding = textView.getPaddingStart();
bounds.left += startPadding;
// textPaint.getTextBounds() has already computed a value for the width of the text,
// however, Paint#measureText() gives a more accurate value.
bounds.right = (int) textPaint.measureText(s, 0, s.length()) + startPadding;
// At this point, (x, y) of the text within the TextView is (bounds.left, bounds.top)
// Draw the bounding rectangle.
Bitmap bitmap = Bitmap.createBitmap(textView.getMeasuredWidth(),
textView.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint rectPaint = new Paint();
rectPaint.setColor(Color.RED);
rectPaint.setStyle(Paint.Style.STROKE);
rectPaint.setStrokeWidth(1);
canvas.drawRect(bounds, rectPaint);
textView.setForeground(new BitmapDrawable(getResources(), bitmap));
}
}
这是我想出的解决方案,它支持多行文本,还可以更改 gravity 属性。下面是结果图和源代码:
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
class CustomTextView : AppCompatTextView {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
val textPaint: Paint = Paint().apply {
isAntiAlias = true
style = Paint.Style.STROKE
strokeWidth = 2f
}
val bounds = ArrayList<Rect>()
val fullBounds = Rect()
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
getBound()
}
private fun getBound() {
text.toString().let { string ->
val lines = string.split("\n")
var offset = 0
lines.forEachIndexed { i, str ->
// replace all tabs with _ char for measuring
val s = str.replace('\t', '_')
// get horizontal bound for each line
val boundHorizontal = Rect()
paint.getTextBounds(s, 0, s.length, boundHorizontal)
boundHorizontal.offset(
paddingStart + (layout?.getPrimaryHorizontal(offset)?.toInt() ?: 0),
0
)
// get vertical bound for each line
val boundVertical = Rect()
getLineBounds(i, boundVertical)
boundVertical.apply {
left = boundHorizontal.left
right = boundHorizontal.right
}
bounds.add(boundVertical)
offset += (s.length + 1)
}
bounds.forEachIndexed { i, rect ->
if (i == 0) {
fullBounds.set(rect)
}
fullBounds.intersectUnchecked(rect)
}
}
}
override fun onDraw(canvas: Canvas) {
canvas.drawRect(fullBounds, textPaint.apply { color = Color.YELLOW })
bounds.forEach {
canvas.drawRect(it, textPaint.apply { color = Color.MAGENTA })
}
super.onDraw(canvas)
}
companion object {
fun Rect.intersectUnchecked(other: Rect) {
if (other.left < left) left = other.left
if (other.right > right) right = other.right
if (other.top < top) top = other.top
if (other.bottom > bottom) bottom = other.bottom
}
}
}
然后通过 XML 添加您的自定义视图:
<com.slaviboy.universaldictionarybg.ApostropheTextView
android:layout_width="150dp"
android:layout_height="200dp"
android:background="#41BADF"
android:gravity="end|bottom"
android:includeFontPadding="false"
android:lineSpacingExtra="0dp"
android:text="This\nis\nmultiline\ntest :D"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
假设我在 TextView
中有以下文本 'ADD TEST' ,如下所示
如您所见,TextView
中的文本与 TextView
的宽度和高度不同。
我想要的是获取 TextView
Y值
您可以使用 textView.getTextSize()
或 textView.getPaint().getTextSize()
获取实际使用的文本大小(以像素为单位)(如 Float
)。
接下来,我们需要文本视图的总高度,我们可以这样找到:
textView.measure(0, 0); // We must call this to let it calculate the heights
int height = textView.getMeasuredHeight();
不过,我们需要的最终尺寸也可以有小数。因此,让我们将其设为浮点数以提高精度:
float totalHeight = (float) height;
现在我们知道了这些值,我们可以计算视图内文本的 y 值:
// The spacing between the views is `totalHeight - textSize`
// We have a spacing at the top and the bottom, so we divide it by 2
float yValue = (totalHeight - textSize) / 2
X值
此外,xValue只是使用时文本视图本身的x值
android:includeFontPadding="false"
.
看看几个 Paint
方法:getTextBounds()
and measureText
。我们可以使用这些来确定文本在 TextView
内的偏移量。一旦确定了 TextView
中的偏移量,我们就可以将其添加到 TextView
本身的位置以确定文本的屏幕坐标(如果需要的话)。
我还发现文章 "Android 101: Typography" 有助于理解排版的一些复杂性。
以下示例查找三个 TextViews
以内的文本边界,并在文本周围绘制一个矩形。该矩形包含 TextView
.
activity_main.xml
用于演示的简单布局。
<android.support.constraint.ConstraintLayout
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:background="@android:color/holo_blue_light"
android:padding="24dp"
android:text="Hello World"
android:textColor="@android:color/black"
android:textSize="50sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:background="@android:color/holo_blue_light"
android:padding="24dp"
android:text="Hello Worldly"
android:textColor="@android:color/black"
android:textSize="50sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/textView1" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:background="@android:color/holo_blue_light"
android:padding="24dp"
android:text="aaaaaaaaaa"
android:textColor="@android:color/black"
android:textSize="50sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/textView2" />
</android.support.constraint.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawTextBounds((TextView) findViewById(R.id.textView1));
drawTextBounds((TextView) findViewById(R.id.textView2));
drawTextBounds((TextView) findViewById(R.id.textView3));
}
private void drawTextBounds(TextView textView) {
// Force measure of text pre-layout.
textView.measure(0, 0);
String s = (String) textView.getText();
// bounds will store the rectangle that will circumscribe the text.
Rect bounds = new Rect();
Paint textPaint = textView.getPaint();
// Get the bounds for the text. Top and bottom are measured from the baseline. Left
// and right are measured from 0.
textPaint.getTextBounds(s, 0, s.length(), bounds);
int baseline = textView.getBaseline();
bounds.top = baseline + bounds.top;
bounds.bottom = baseline + bounds.bottom;
int startPadding = textView.getPaddingStart();
bounds.left += startPadding;
// textPaint.getTextBounds() has already computed a value for the width of the text,
// however, Paint#measureText() gives a more accurate value.
bounds.right = (int) textPaint.measureText(s, 0, s.length()) + startPadding;
// At this point, (x, y) of the text within the TextView is (bounds.left, bounds.top)
// Draw the bounding rectangle.
Bitmap bitmap = Bitmap.createBitmap(textView.getMeasuredWidth(),
textView.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint rectPaint = new Paint();
rectPaint.setColor(Color.RED);
rectPaint.setStyle(Paint.Style.STROKE);
rectPaint.setStrokeWidth(1);
canvas.drawRect(bounds, rectPaint);
textView.setForeground(new BitmapDrawable(getResources(), bitmap));
}
}
这是我想出的解决方案,它支持多行文本,还可以更改 gravity 属性。下面是结果图和源代码:
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
class CustomTextView : AppCompatTextView {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
val textPaint: Paint = Paint().apply {
isAntiAlias = true
style = Paint.Style.STROKE
strokeWidth = 2f
}
val bounds = ArrayList<Rect>()
val fullBounds = Rect()
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
getBound()
}
private fun getBound() {
text.toString().let { string ->
val lines = string.split("\n")
var offset = 0
lines.forEachIndexed { i, str ->
// replace all tabs with _ char for measuring
val s = str.replace('\t', '_')
// get horizontal bound for each line
val boundHorizontal = Rect()
paint.getTextBounds(s, 0, s.length, boundHorizontal)
boundHorizontal.offset(
paddingStart + (layout?.getPrimaryHorizontal(offset)?.toInt() ?: 0),
0
)
// get vertical bound for each line
val boundVertical = Rect()
getLineBounds(i, boundVertical)
boundVertical.apply {
left = boundHorizontal.left
right = boundHorizontal.right
}
bounds.add(boundVertical)
offset += (s.length + 1)
}
bounds.forEachIndexed { i, rect ->
if (i == 0) {
fullBounds.set(rect)
}
fullBounds.intersectUnchecked(rect)
}
}
}
override fun onDraw(canvas: Canvas) {
canvas.drawRect(fullBounds, textPaint.apply { color = Color.YELLOW })
bounds.forEach {
canvas.drawRect(it, textPaint.apply { color = Color.MAGENTA })
}
super.onDraw(canvas)
}
companion object {
fun Rect.intersectUnchecked(other: Rect) {
if (other.left < left) left = other.left
if (other.right > right) right = other.right
if (other.top < top) top = other.top
if (other.bottom > bottom) bottom = other.bottom
}
}
}
然后通过 XML 添加您的自定义视图:
<com.slaviboy.universaldictionarybg.ApostropheTextView
android:layout_width="150dp"
android:layout_height="200dp"
android:background="#41BADF"
android:gravity="end|bottom"
android:includeFontPadding="false"
android:lineSpacingExtra="0dp"
android:text="This\nis\nmultiline\ntest :D"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />