오늘도 삽질중

Android Gradient rounded corner programmatically 본문

안드로이드

Android Gradient rounded corner programmatically

Choi3950 2021. 12. 22. 00:06
반응형

Multi Gradient 또는 단일 Gradient 를 주고 싶거나

모서리에 라운딩이 필요한경우 유용하게 사용할수 있다

 

 

xml

 <View
        android:id="@+id/bg_view"
        android:layout_width="120dp"
        android:layout_height="120dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

 

kt

    fun View.bgMultiGradient(colorArray: IntArray, positionArray: FloatArray , rounded: Float = 0f) {
        val sf = object : ShapeDrawable.ShaderFactory() {
            override fun resize(width: Int, height: Int): Shader {
                val g = LinearGradient(
                    0f, 0f, 0f, this@bgMultiGradient.height.toFloat(),
                    colorArray, positionArray, Shader.TileMode.CLAMP
                )
                return g
            }
        }

        val r = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP ,
            rounded ,
            this.resources.displayMetrics)

        val paintDrawable = PaintDrawable().apply {
            shape = if (rounded == 0f) RectShape()
                    else RoundRectShape(
                        floatArrayOf(
                            r,r,r,r,r,r,r,r
                        ),null,null
                    )

            shaderFactory = sf
        }

        background = paintDrawable
    }

 

사용예시

 

        binding.bgView.bgMultiGradient(
            intArrayOf(Color.GREEN, Color.YELLOW, Color.RED, Color.BLACK),
            floatArrayOf(0f,0.45f,0.78f,1f),
            20f
        )

 

 

결과화면

반응형
Comments