自定义ImageSpan之行居中,可设置左右间距

自定义 ImageSpan 之行居中,可设置左右间距

image-20241126200147

实现功能:

  1. Image 所在行居中显示
  2. 可以设置图片和前后文本的间距
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.text.style.ImageSpan

open class MarginImageSpan(
context: Context,
drawableRes: Int,
val l: Int = 0,
val r: Int = 0
) : ImageSpan(context, drawableRes) {

override fun getSize(
paint: Paint,
text: CharSequence?,
start: Int,
end: Int,
fm: Paint.FontMetricsInt?
): Int {
val d: Drawable = drawable
val rect = d.bounds

if (fm != null) {
val var7 = Paint.FontMetricsInt()
paint.getFontMetricsInt(var7)
fm.ascent = var7.ascent
fm.descent = var7.descent
fm.top = var7.top
fm.bottom = var7.bottom
}

return l + rect.right + r
}

override fun draw(
canvas: Canvas,
text: CharSequence,
start: Int,
end: Int,
x: Float,
top: Int,
y: Int,
bottom: Int,
paint: Paint
) {
// image to draw
val b = drawable
// font metrics of text to be replaced
val fm = paint.fontMetricsInt
var transY = ((y + fm.descent + y + fm.ascent) / 2 - b.bounds.bottom / 2)
// to check the last line.(当 image 在单独一行显示时可能会存在这个问题)
if (transY > bottom - b.bounds.bottom) transY = bottom - b.bounds.bottom
//
val transX = x + l
canvas.save()
canvas.translate(transX, transY.toFloat())
b.draw(canvas)
canvas.restore()
}
}

使用场景

1
2
3
4
5
6
val spanStr = SpannableStringBuilder("#")
spanStr.append(data.seriesName)
val imageSpan = MarginImageSpan(context, R.drawable.home_ic, 0, 3.dp)
// 创建 ImageSpan
spanStr.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

作者

Dench

发布于

2024-11-26

更新于

2024-11-26

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×