package com.adealink.weparty.commonui.util

import android.graphics.Paint


object FontUtils {

    fun ellipsizeStringByWidth(text: String, paint: Paint, maxWidth: Double): String {
        val textWidth = paint.measureText(text)
        if (textWidth <= maxWidth) {
            return text // 文本宽度未超出,直接返回
        }

        val ellipsisWidth = paint.measureText("...")
        if (maxWidth < ellipsisWidth) {
            return "" // 最大宽度小于省略号宽度,返回空字符串
        }

        var maxLength = 0
        var currentWidth = 0f
        while (currentWidth + ellipsisWidth <= maxWidth && maxLength < text.length) {
            currentWidth += paint.measureText(text[maxLength].toString())
            maxLength++
        }

        return if (maxLength == text.length) {
            text // 文本长度未超出,直接返回
        } else {
            text.substring(0, maxLength) + "..."
        }
    }
}

