短視頻軟件開發Java/Kotlin 獲取文字、字符串像素長度方法

假設
試想我們需要在一個 font_max 的長度空間,任意的添加文字,但不能換行,於是,我們就要保證字體的大小能放入這個 font_max 長度,那就需要檢驗文字的像素長度,他可能包含漢字、英文、符號等,所以不能簡單計算。

方法

// 拿到圖片的 Graphics2D 畫圖對象
val imageGraphics: Graphics2D = image.createGraphics()
// 設置字體大小
var fontSize = info.font_size
// 設置字體 style
var font = Font("微軟雅黑",Font.PLAIN ,fontSize)
// 獲取文字 text 的像素長度
var textWidth = font.getStringBounds(text, imageGraphics.fontRenderContext).width.toInt()
// 只要比 font_max 大,放不下,就按 font_sub 遞減,並重新比較
while (textWidth > info.font_max) {
    fontSize -= info.font_sub
    font = Font("黑體",Font.PLAIN , fontSize)
    textWidth = font.getStringBounds(text, imageGraphics.fontRenderContext).width.toInt()
}

其中,獲取字符串像素長度的方法是:

val textWidth = font.getStringBounds(text, Graphics2D.fontRenderContext).width.toInt()

Java 同理,庫相同

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章