안드로이드 개발 팁 #8 - TextView에 linear gradient color 적용하기
위 그림과 같이 가로 방향으로 텍스트의 색이 다른 TextView를 구현하려면 어떻게 해야 할까요? 이번 프로젝트의 시작화면에서 보여줄 앱 이름에 이를 적용해달라고 요청을 받았구요. 검색된 자료들을 참고하여 TextView 클래스의 확장 메소드를 만들어 보았습니다.
TextView에 linear gradient color 적용하는 확장 메소드
fun TextView.setTextColorAsLinearGradient(colors: Array<Int>) {
if (colors.isEmpty()) {
return
}
setTextColor(colors[0])
this.paint.shader = LinearGradient(
0f,
0f,
paint.measureText(this.text.toString()),
this.textSize,
colors.toIntArray(),
arrayOf(0f, 1f).toFloatArray(),
Shader.TileMode.CLAMP
)
}
두 가지 색으로 linear gradient color 적용
아래 코드는 좌측 끝은 빨간 색, 우측 끝은 파란색으로 설정하는 linear gradient color를 TextView에 적용한 예입니다.
tvExample.setTextColorAsLinearGradient(arrayOf(
Color.parseColor("#FF0000"),
Color.parseColor("#0000FF")
))

[광고] STEEM 개발자 커뮤니티에 참여 하시면, 다양한 혜택을 받을 수 있습니다.
Upvoted! Thank you for supporting witness @jswit.
