Android_app

[JetPack Compose] Text() 함수 인자 분석

하니_즐거운하루 2022. 11. 17. 16:58

: Composable Text() 함수 사용법을 인자값을 변경해 가면서 테스트 해봤습니다.

 

 

 

 함수 선언  : Text.kt 에 정의

 

 

함수인자

Params:
    text - The text to be displayed.
    modifier - Modifier to apply to this layout node.
    color - Color to apply to the text. If Color.Unspecified, and style has no color set, this will be LocalContentColor.
    fontSize - The size of glyphs to use when painting the text. See TextStyle.fontSize.
    fontStyle - The typeface variant to use when drawing the letters (e.g., italic). See TextStyle.fontStyle.
    fontWeight - The typeface thickness to use when painting the text (e.g., FontWeight.Bold).
    fontFamily - The font family to be used when rendering the text. See TextStyle.fontFamily.
    letterSpacing - The amount of space to add between each letter. See TextStyle.letterSpacing.
    textDecoration - The decorations to paint on the text (e.g., an underline). See TextStyle.textDecoration.
    textAlign - The alignment of the text within the lines of the paragraph. See TextStyle.textAlign.
    lineHeight - Line height for the Paragraph in TextUnit unit, e.g. SP or EM. See TextStyle.lineHeight.
    overflow - How visual overflow should be handled.
    softWrap - Whether the text should break at soft line breaks. If false, the glyphs in the text will be positioned as if there was unlimited horizontal space. If softWrap is false, overflow and TextAlign may have unexpected effects.
    maxLines - An optional maximum number of lines for the text to span, wrapping if necessary. If the text exceeds the given number of lines, it will be truncated according to overflow and softWrap. If it is not null, then it must be greater than zero.
    onTextLayout - Callback that is executed when a new text layout is calculated. A TextLayoutResult object that callback provides contains paragraph information, size of the text, baselines and other details. The callback can be used to add additional decoration or functionality to the text. For example, to draw selection around the text.
    style - Style configuration for the text such as color, font, line height etc.

 인자 테스트

 

text

 : 화면에 표시될 텍스트 내용

  // text
Text("text")
Text("text.repeat() ==> "+"1".repeat(5))
Text("1234567890".substring(2,5))               // "345" >>  startIndex<= X <endIndex
Text("1234567890".substring(2..4))   // "345" >>  range  <=  X =<
Text("1234567890".substring(3))         // "4567890"   >> startIndex
Text(1234567890.toString())                     // "1234567890"
Text("text".plus(" others"))              // "text others"
Text("text".length.toString())                  // 4
Text("1"+"2"+"3")                   // 123
Text("text.hashCode==> "+"1".hashCode().toString())
Text("1234567890".drop(2))                  // 34567890
Text("1234567890".dropLast(2))              // 12345678

// dropWhile , dropLastWhile{}  >> 조건을 만족하지 않는 문자가 나올때까지 제거
Text("1234567890ABCDE".dropWhile { !it.isUpperCase()})      // ABCED
Text("1234567890ABCDE".dropLastWhile { !it.isDigit()})      // "1234567890"

 

color    

  :  텍스트 색깔지정

 //Text Color Test
Text("Color red",color=Color.Red)
Text("Color blue",color=Color.Blue)
Text("Color green",color=Color.Green)
Text("Color yellow",color=Color.Yellow)
Text("Color cyan",color=Color.Cyan)
Text("Color gray",color=Color.Gray)

 

fontSize

  : 글자크기 설정 ( sp)

// font Size
Text("fontSize is 5sp", fontSize = 5.sp)
Text("fontSize is 10sp", fontSize = 10.sp)
Text("fontSize is 20sp", fontSize = 20.sp)
Text("fontSize is 30sp", fontSize = 30.sp)
Text("fontSize is 50sp", fontSize = 50.sp)

 

fontStyle

  : 2가지 종류가 있습니다.

// fontStyle
Text("fontStyle is Italic", fontStyle = FontStyle.Italic)
Text("fontStyle is Normal", fontStyle = FontStyle.Normal)

 

 

 

fontWeight

 : 화면에 그려질 글자의 두께설정 

// fontWeight
Text("FontWeight is thin", fontSize=24.sp, fontWeight = FontWeight.Thin)
Text("FontWeight is extra light", fontSize=24.sp,fontWeight = FontWeight.ExtraLight)
Text("FontWeight is light", fontSize=24.sp,fontWeight = FontWeight.Light)
Text("FontWeight is normal",fontSize=24.sp, fontWeight = FontWeight.Normal)
Text("FontWeight is medium",fontSize=24.sp, fontWeight = FontWeight.Medium)
Text("FontWeight is semi bold",fontSize=24.sp, fontWeight = FontWeight.SemiBold)
Text("FontWeight is bold",fontSize=24.sp, fontWeight = FontWeight.Bold)
Text("FontWeight is ExtraBold", fontSize=24.sp,fontWeight = FontWeight.ExtraBold)
Text("FontWeight is black",fontSize=24.sp, fontWeight = FontWeight.Black)

갤럭시 S6 plus

 

fontFamily

  : 폰트 종류 선택하기

// fontFamily
Text("fontFamily ==> Default", fontFamily = FontFamily.Default)
Text("fontFamily ==> Serif", fontFamily = FontFamily.Serif)
Text("fontFamily ==> SansSerif", fontFamily = FontFamily.SansSerif)
Text("fontFamily ==> Monospace", fontFamily = FontFamily.Monospace)
Text("fontFamily ==> Cursive", fontFamily = FontFamily.Cursive)

letterSpacing

  : 글자사이 간격 설정

// letterSpacing
Text("letterSpacing ==> Unspecified", letterSpacing = TextUnit.Unspecified)
Text("letterSpacing ==> 0.sp", letterSpacing = 0.sp)
Text("letterSpacing ==> 1.sp", letterSpacing = 1.sp)
Text("letterSpacing ==> 2.sp", letterSpacing = 2.sp)
Text("letterSpacing ==> 5.sp", letterSpacing = 5.sp)
Text("letterSpacing ==> 0.062.em", letterSpacing = 0.062.em)
Text("letterSpacing ==> 0.124.em", letterSpacing = 0.124.em)
Text("letterSpacing ==> 0.312.em", letterSpacing = 0.312.em)

 

textDecoration

 : 가운데/아래쪽 라인을 넣을경우 사용

Text("textDecoration ==> None", textDecoration = TextDecoration.None)
Text("textDecoration ==> LineThrough", textDecoration = TextDecoration.LineThrough)
Text("textDecoration ==> Underline", textDecoration = TextDecoration.Underline)

 

textAlign

  : textAlign 을 적용하기전 기본적인 border를 사용해 실제 크기를 먼저 확인 합니다.

Text("textAlign ", modifier = Modifier.border(BorderStroke(1.dp , Color.Red)) )

 ==> textAlign  설정이 동작하기 위해서는 기본적으로 width, height 크기를 변경해야 합니다.

Text("textAlign ",
    modifier = Modifier
        .border(BorderStroke(1.dp , Color.Red))
        .width(300.dp)
        .height(50.dp))

 

// textAlign
Text("textAlign ==> Center ",  textAlign = TextAlign.Center, modifier = Modifier.border(BorderStroke(1.dp , Color.Red)).width(300.dp).height(50.dp))
Text("textAlign ==> Left ",  textAlign = TextAlign.Left, modifier = Modifier.border(BorderStroke(1.dp , Color.Red)).width(300.dp).height(50.dp))
Text("textAlign ==> Right ",  textAlign = TextAlign.Right, modifier = Modifier.border(BorderStroke(1.dp , Color.Red)).width(300.dp).height(50.dp))
Text("textAlign ==> Start ",  textAlign = TextAlign.Start, modifier = Modifier.border(BorderStroke(1.dp , Color.Red)).width(300.dp).height(50.dp))
Text("textAlign ==> End ",  textAlign = TextAlign.End, modifier = Modifier.border(BorderStroke(1.dp , Color.Red)).width(300.dp).height(50.dp))
Text("textAlign ==> Justify ",  textAlign = TextAlign.Justify, modifier = Modifier.border(BorderStroke(1.dp , Color.Red)).width(300.dp).height(50.dp))

 : Left , Right 보다는 Start ,End 사용을 권장합니다.  (RTL or LTR 사용의 경우  달라짐.)

 

lineHeight

 : 2줄이상의 텍스트의 경우 줄사이의 간격을 설정합니다.

   기본적으로 폰트 높이가 12.sp 이므로 이보다 작으면 글자가 겹쳐서 보입니다.

// lineHeight
Text("lineHeight ==> Unspecified.\nHello Android", lineHeight = TextUnit.Unspecified)
Spacer(modifier = Modifier.size(30.dp))

Text("lineHeight ==> 5.sp\n Hello Android", lineHeight = 5.sp)
Spacer(modifier = Modifier.size(30.dp))

Text("lineHeight ==> 10.sp\n Hello Android", lineHeight = 10.sp)
Spacer(modifier = Modifier.size(30.dp))
Text("lineHeight ==> 20.sp\n Hello Android", lineHeight = 20.sp)

Spacer(modifier = Modifier.size(30.dp))

 

overflow

: 텍스트의 길이가 화면을 벗어날경우 처리

// overflow
Text("overflow ==> Clip     12345", overflow = TextOverflow.Clip, modifier = Modifier.width(170.dp).height(35.dp))
Text("overflow ==> Ellipsis 12345", overflow = TextOverflow.Ellipsis, maxLines = 1,modifier = Modifier.width(170.dp).height(30.dp))
Text("overflow ==> Visible 12345", overflow = TextOverflow.Visible, modifier = Modifier.width(170.dp).height(30.dp))

 

 

옵션 의미
Clip (자르다) 긴텍스트의  넘치는 부분을 잘라낸다.
Ellipsis (생략) 긴텍스트의 경우  마지막에 "..." 로 표시합니다.
Visible 바운더리 상관없이  긴텍스트 모두 표시.

 

softWrap  : 자동 줄바꿈

 : 기본값은 true 입니다.

// softWrap  (자동줄바꿈)
Text("softWrap is true (12345567890)", softWrap = true,modifier = Modifier.width(170.dp))
Spacer(modifier = Modifier.size(30.dp))
Text("softWrap is false (12345567890)", softWrap = false,modifier = Modifier.width(170.dp))

 

maxLines

 : maxLines 는  최대 표시될 라인갯수를 설정함. 미사용시  모든라인 표시합니다.

// maxLines
Text("1234567890".repeat(20),modifier=Modifier.border(BorderStroke(1.dp , Color.Red)))
Spacer(modifier = Modifier.size(30.dp))
Text("1234567890".repeat(20), maxLines = 2,modifier=Modifier.border(BorderStroke(1.dp , Color.Green)))
Spacer(modifier = Modifier.size(30.dp))
Text("1234567890".repeat(20), maxLines = 4,modifier=Modifier.border(BorderStroke(1.dp , Color.Blue)))
Spacer(modifier = Modifier.size(30.dp))
Text("1234567890".repeat(20), maxLines = 6,modifier=Modifier.border(BorderStroke(1.dp , Color.Magenta)))
Spacer(modifier = Modifier.size(30.dp))

 

 

 

onTextlayout

 :  파라미터로 TextLayoutResult 를 가지는 Callback 함수를 이용해 새로운 decoration 적용시 사용합니다.

 

Text("onTextLayout", fontSize = 24.sp,textDecoration=TextDecoration.Underline)

위의  Underline 이 포함된 텍스트의 Underline 색깔 및 위치를 변경하고 3번째 문자의 배경색을 변경할려고 할경우 간단히 할수 있습니다.

 

    //onTextLayout
    val firstBaseline = remember { mutableStateOf(0f) }
    val thirdCharRect = remember { mutableStateOf<Rect>(Rect.Zero,) }
    Text("onTextLayout", fontSize = 24.sp,
        onTextLayout = {
            firstBaseline.value=it.firstBaseline
            thirdCharRect.value = it.getBoundingBox(2)
        },
        modifier = Modifier.drawWithContent {
            drawRect(Color.Green, Offset(thirdCharRect.value.left,thirdCharRect.value.top),
                size= Size(thirdCharRect.value.width, thirdCharRect.value.height),
            )
            drawContent()
            drawLine(Color.Red, Offset(0f,firstBaseline.value), Offset(size.width,firstBaseline.value))
    })

  ▶ firstBaseline 및 thirdCharRect 변수를 remember를 이용해 선언합니다.

  ▶ UnderLine 대신 TextLayoutResult.firstBaseline 값 사용

  ▶ 3번째 문자 Rect 좌표구하기  (TextLayoutResult.getBondingBox(2))

  ▶ drawWithContent 를 이용해 새로 그리기

 

 

style

// Style
Text("style : TextStyle: default ",style=TextStyle())
Text("style : TextStyle:Color.Red ",style=TextStyle(Color.Red))
Text("style : TextStyle:fontSize=24.sp ",style=TextStyle(fontSize=24.sp))
Text("style : TextStyle:fontWeight = FontWeight.Bold ",style=TextStyle(fontWeight = FontWeight.Bold))
Text("style : TextStyle:baselineShift(3f) ",style=TextStyle(baselineShift = BaselineShift(3f)))
Text("style : TextStyle:background = Color.Gray",style=TextStyle(background = Color.Gray))

modifier

  → border 

    val strName = it.name    --> aerg
    Text(strName,
        modifier = Modifier
            .width(80.dp)
            .border(2.dp,Color.Red, RectangleShape),
        textAlign = TextAlign.Center,
    )
    Spacer(modifier = Modifier.size(20.dp))
    val strAddress =String.format("%20s",it.address)  
    Text(strAddress,
        modifier = Modifier
            .width(200.dp)
            .border(2.dp,Color.Blue, CircleShape))

Modifier border,width 사용

반응형