Compose Custom Font 설정하기

woobin·2023년 1월 6일
0

Jetpack Compose

목록 보기
2/4

디자이너와 작업하다보면 색상, 폰트, 기본 컴포넌트들을 모아놓고 사용해야하는 경우가 있습니다.
그 중 오늘은 커스텀 폰트를 정의하여 편하게 사용하는 방법을 소개하고자 합니다.


폰트 추가하기

원하는 폰트를 다운받은 후 res/font 폴더에 넣기만 하면 폰트 추가는 간단하게 할 수 있습니다.

정의하기

저는 FontUtil.kt 라는 파일을 만들어 디자이너의 폰트 DesignStyle을 모아놓았습니다.

먼저 FontFamily와 DesignStyle이 공통으로 사용하는 값들을 먼저 세팅해줍니다.

private val myFontFamily = FontFamily(
	Font(R.font.spoqahan_sans_neo_bold, weight = FontWeight.Bold),
	Font(R.font.spoqahan_sans_neo_medium, weight = FontWeight.Medium),
	Font(R.font.spoqahan_sans_neo_regular, weight = FontWeight.Normal)
)

private val baseTextStyle = TextStyle(
	textAlign = TextAlign.Start,
	color = Color.Black,
	fontWeight = FontWeight.Normal,
	fontStyle = FontStyle.Normal,
    // 아래 속성은 기본폰트패딩을 없애주는 속성인데 작동은하지만 올바른 사용방법인지는 잘 모르겠습니다.
	platformStyle = PlatformTextStyle(includeFontPadding = false)
)

다음으로 DesignStyle대로 사용할 이름들을 정의 한 후 Custom하여 스타일들을 정의해줍니다.

enum class MyTextStyle {
	H1,
    H2,
    Body1
}

@Composable
fun getTextStyle(style: MyTextStyle): androidx.compose.ui.text.TextStyle {
	return when(style) {
    	MyTextStyle.H1 -> {
        	baseTextStyle.copy(
	        	fontFamily = myFontFamily,
	            fontSize = dpToSp(26.dp),
    	        lineHeight = dpToSp(34.dp),
        	    letterSpacing = dpToSp((-1.0).dp)
            )
        }
        MyTextStyle.H2 -> {
        	baseTextStyle.copy(
            	fontFamily = myFontFamily,
                fontSize = dpToSp(24.dp),
                lineHeight = dpToSp(32.dp),
                letterSpacing = dpToSp((-1.0).dp)
            )
        }
        MyTextStyle.BODY1 -> {
        	baseTextStyle.copy(
            	fontFamily = myFontFamily,
                fontSize = dpToSp(16.dp),
                lineHeight = dpToSp(24.dp),
                letterSpacing = dpToSp((-0.4).dp)
            )
		}
    }
}

사용하기

Composable에서 사용할때에는 아래처럼 사용합니다.

@Composable
fun MyStyleText(content: String) {
    Text (
        text = content,
        style = getTextStyle(FontUtil.MyTextStyle.H1)
    )
}

개별적으로 바꾸고싶은 속성들이 있다면 아래처럼 사용할 수 있습니다.

@Composable
fun MyStyleText(content: String) {
    Text (
        text = content,
        style = getTextStyle(FontUtil.MyTextStyle.H1)
        	.copy(color = Color.White)
    )
}

마치며 🦊

오늘은 폰트 추가 방법과 디자이너와 개발할 때 유용한 폰트를 커스텀하여 모아두고 사용하는 방법을 알아보았습니다.
Text 컴포넌트를 매번 만들어 스타일을 정의하여 쓰는 방법 보다는 위의 방법이 더욱 편리하고 빠른 방법이라고 생각합니다.

혹시나 잘못된 부분이나 부족한 부분이 있다면 댓글로 알려주시면 열심히 배우겠습니다.
읽어주셔서 감사합니다.

0개의 댓글