kotlin multiplatform 高亮字体

package com.anker.akblebusinessui.pair.firmware.components

import androidx.compose.material.LocalTextStyle

import androidx.compose.material.Text

import androidx.compose.runtime.Composable

import androidx.compose.ui.graphics.Color

import androidx.compose.ui.text.SpanStyle

import androidx.compose.ui.text.TextStyle

import androidx.compose.ui.text.buildAnnotatedString

import androidx.compose.ui.text.font.FontWeight

import androidx.compose.ui.text.withStyle

@Composable

fun HighlightedText(

text: String,

searchQuery: String,

normalColor: Color = Color.Black,

highlightColor: Color = Color.Red,

style: TextStyle =LocalTextStyle.current,

ignoreCase: Boolean =true

) {

val annotatedString =buildAnnotatedString {

        if (searchQuery.isEmpty()) {

// 没有搜索词,显示普通文本

            withStyle(SpanStyle(color = normalColor)){

                append(text)

}

        }else {

var currentIndex =0

            val searchPattern =if (ignoreCase) {

searchQuery.lowercase()

}else {

searchQuery

}

val textToSearch =if (ignoreCase) {

text.lowercase()

}else {

text

}

// 查找所有匹配的位置

            while (currentIndex < text.length) {

val index = textToSearch.indexOf(searchPattern, currentIndex)

if (index == -1) {

// 没有更多匹配,添加剩余文本

                    withStyle(SpanStyle(color = normalColor)){

                        append(text.substring(currentIndex))

}

                    break

                }else {

// 添加匹配前的文本

                    if (index > currentIndex) {

withStyle(SpanStyle(color = normalColor)){

                            append(text.substring(currentIndex, index))

}

                    }

// 添加高亮的匹配文本

                    withStyle(SpanStyle(color = highlightColor,fontWeight = FontWeight.Bold)){

                        append(text.substring(index, index + searchQuery.length))

}

                    currentIndex = index + searchQuery.length

                }

}

}

}

    Text(

text = annotatedString,

style = style

)

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容