今天來寫寫關於ImageSpan,透過ImageSpan可以簡單做到在TextView文字中插入圖片。
最簡單的用法如下
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
val text = "一二三四五六七八九十" | |
val imageSpan = ImageSpan(this,R.drawable.ic_baseline_check_circle_24) | |
val spannableStringBuilder = SpannableStringBuilder() | |
spannableStringBuilder.append(text) | |
spannableStringBuilder.setSpan(imageSpan,4,5,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) | |
textView.setText(spannableStringBuilder) | |
} | |
} |
可以發現,Icon是貼齊在TextView該行的底部,這邊ImageSpan有verticalAlignment屬性可以設定,預設是ALIGN_BOTTOM,另外一個是ALIGN_BASELINE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val imageSpan = ImageSpan(this,R.drawable.ic_baseline_check_circle_24,ImageSpan.ALIGN_BASELINE) |
效果就如同ALIGN_BASELINE的字面意思,以文字的基底為準,可以看圖明顯看到Icon是貼齊文字的底部。
但屬性就只有這兩種可以設定,那如果想要實現Icon位置處在該行的正中間,該怎麼做呢?
簡單的想法,就是繪製Icon的時候,其位置調整到該行的中間,因此這邊繼承ImageSpan並重寫draw這個function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class VerticalImageSpan(context: Context, resId: Int) : ImageSpan(context, resId) { | |
override fun draw(canvas: Canvas, text: CharSequence?, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) { | |
canvas.save() | |
val transY = top + (bottom - top) / 2 - drawable.bounds.height() / 2 | |
canvas.translate(x, transY.toFloat()) | |
drawable.draw(canvas) | |
canvas.restore() | |
} | |
} |
再來將原本使用ImageSpan改為所寫的VerticalImageSpan,就可以做到ImageSpan垂直置中的效果囉
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val imageSpan = VerticalImageSpan(this, R.drawable.ic_baseline_check_circle_24) |