본문 바로가기

Android - 기능

[Android] OutLineTextView - 글자 외곽선 더하기

#What

TEXT 글자에 OutLine(외곽선) 추가 하는 방법

  1. attrs.xml 생성
  2. CustomView 생성
  3. Layout 적용

 

흰 TEXT + 초록 외곽선

#attrs.xml

 

 

 

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="OutLineTextView">
        <attr name ="textStrokeWidth" format ="float"/> //외곽선 width
        <attr name ="textStrokeColor" format ="color"/> //외곽선 color
    </declare-styleable>
</resources>

 

#CustomTextView

package com.example.qt.web.view

import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import com.example.qt.R

class OutLineTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : androidx.appcompat.widget.AppCompatTextView(context, attrs, defStyleAttr) {

    private var strokeColor: Int
    private var strokeWidthVal: Float

    init {
    	//attributes 가져오기
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.OutLineTextView)
        strokeWidthVal = typedArray.getFloat(R.styleable.OutLineTextView_textStrokeWidth, 3f)
        strokeColor = typedArray.getColor(R.styleable.OutLineTextView_textStrokeColor, Color.WHITE)
    }

    override fun onDraw(canvas: Canvas?) {
        //draw stroke
        val states: ColorStateList = textColors
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = strokeWidthVal
        setTextColor(strokeColor)
        super.onDraw(canvas)

        //draw fill
        paint.style = Paint.Style.FILL
        setTextColor(states)
        super.onDraw(canvas)
    }
}

 

#Layout 적용

    <com.example.qt.web.view.OutLineTextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="OutLineTextTest"
        android:textColor="@color/white"
        android:textSize="40sp"
        android:gravity="center"
        app:textStrokeColor="@android:color/holo_green_light" //생성한 attribute 속성 설정
        app:textStrokeWidth="30" />                           //생성한 attribute 속성 설정

 

 


 

문제 있을시 알려 주세요.

 

좋은 하루 되세요!