Canvas로 꺾은선 그래프를 그리기 전에 먼저 drawLine() 함수를 알아야 한다.
아래의 사진은 drawLine()을 이용해 그린 꺾은선 그래프이다.

Screenshot 2024-06-19 at 2 45 10 PM

drawLine()

drawLine()의 기본 매개변수 설명

Canvas(modifier = Modifier.fillMaxWidth().aspectRatio(1f)) {
    drawLine(
        color = Color(0xFF0C964A),
        start = Offset(0f, 0f),
        end = Offset(size.width/2, 0f ),
        strokeWidth = 20f
    )
}

image

start 매개변수는 선의 시작점,
end 매개변수는 선의 끝점이다.
strokeWidth는 선의 두께를 결정한다.

선끝 모양 변경

cap 매개변수를 이용해 둥근 선을 만들 수 있다.

Canvas(modifier = Modifier.fillMaxWidth().aspectRatio(1f)) {
    drawLine(
        color = Color(0xFF0C964A),
        start = Offset(0f, 0f),
        end = Offset(size.width/2, 0f ),
        strokeWidth = 20f,
        cap = StrokeCap.Round
    )
}

image

<div style="font-size: 18">점선</div> pathEffect를 통해 점선으로 화면에 나타낼 수 있다. dashPathEffect()의 첫번 째 매개변수의 크기를 조절하면 점선의 간격을 조절할 수 있다. 아래의 사진을 보면 이해가 빠를것 이다.

Canvas( modifier = Modifier.fillMaxWidth().aspectRatio(1f)
) {
    drawLine(
        color = Color(0xFF0C964A),
        start = Offset(0f, 0f),
        end = Offset(size.width / 2, 0f),
        strokeWidth = 20f,
        cap = StrokeCap.Round,
        pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 40f), 0f),
//      pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 20f), 0f)
    )
}
  • 40f인 경우
    image

  • 20f인 경우
    image

drawText()

Canvas내에서 text를 ui에 나타내고 싶을 때 사용하는 함수이다.
drawText()를 사용하기 위해서는 TextMeasurer, TextLayoutResult 객체가 필요하다.

val textMeasurer = rememberTextMeasurer()
  val text = "Hello"
  val textLayoutResult = remember(text) {
      textMeasurer.measure(text)
  }
  Canvas(
      modifier = Modifier
          .fillMaxWidth()
          .aspectRatio(1f)
  ) {
      drawLine( .. )
      drawText(
          textLayoutResult = textLayoutResult,
          color = Color.Black,
          topLeft = Offset(size.width / 2, 0f)
      )
  }

image

drawText는 좌상단의 빨간점을 기준으로 Offset를 결정한다. 빨간점은 이해하기 쉽도록 임의로 표시했다.

만약 drawText의 위치를 가운데 정렬하거나 우측 끝에 맞추고 싶다면 다음과 같이 코드를 작성하면된다.

drawText(
    textLayoutResult = textLayoutResult,
    color = Color.Black,
    // 가운데 정렬
    topLeft = Offset(size.width/2 - textLayoutResult.size.width/2 , 0f)
    // 우측 정렬
    // topLeft = Offset(size.width/2 - textLayoutResult.size.width , 0f)
)
  • 가운데 정렬
    image

  • 우측 정렬
    image