package com.example.customviewapplication
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import androidx.core.view.isVisible
class CustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
isAntiAlias = true
maskFilter = BlurMaskFilter(20F, BlurMaskFilter.Blur.INNER)
}
private val chartPaint = Paint().apply {
style = Paint.Style.STROKE
color = Color.WHITE
strokeWidth = 3f
}
private val rectF = RectF()
private val path = Path()
private var colors = intArrayOf(Color.RED, Color.GREEN, Color.RED)
private var ratio = floatArrayOf(0.6f, 0.8f, 1f)
init {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomView, defStyleAttr, 0)
typedArray.recycle()
}
override fun onDraw(canvas: Canvas?) {
canvas ?: return
val paddingLeft = paddingLeft.toFloat()
val paddingRight = paddingRight.toFloat()
val paddingTop = paddingTop.toFloat()
val availableWidth = width - paddingLeft - paddingRight
val pointX = paddingLeft
paint.shader = createShader(colors, ratio)
val pointTop = paddingTop
rectF.set(pointX, pointTop, pointX + availableWidth, pointTop + height)
canvas.drawRoundRect(rectF, 6f, 6f, paint)
// for (i in 0 until 360 step 10) {
// canvas.drawLine(
// i.toFloat(),
// 100 + 100 * Math.cos(i / 180.0 * Math.PI).toFloat(),
// i + 10f,
// 100 + 100 * Math.cos((i + 10) / 180.0 * Math.PI).toFloat(),
// paint
// )
// }
// draw first cubic line
path.reset()
path.moveTo(availableWidth / 5f, height.toFloat())
path.cubicTo(availableWidth / 2, height / 3f, availableWidth * 2 / 3, height * 1.5f, width.toFloat(), height / 3f)
chartPaint.style = Paint.Style.STROKE
chartPaint.color = Color.WHITE
chartPaint.strokeWidth = 3f
chartPaint.shader = null
canvas.drawPath(path, chartPaint)
// complete path to fill below first cubic
path.lineTo(width.toFloat(), height.toFloat())
path.lineTo(availableWidth / 5f, height.toFloat())
// chartPaint.shader = createFillShader(
// width / 2f,
// height / 2f,
// width / 2f,
// height.toFloat()
// )
chartPaint.color = Color.argb(60, 255, 255, 255)
chartPaint.style = Paint.Style.FILL_AND_STROKE
canvas.drawPath(path, chartPaint)
super.onDraw(canvas)
}
private fun createShader(colors: IntArray, ratio: FloatArray): Shader {
return SweepGradient(
width / 2f,
height / 2f,
colors,
ratio
)
}
// chartPaint.shader = createFillShader(
// width.toFloat(),
// height.toFloat(),
// availableWidth / 5f,
// height / 3f
// )
private fun createFillShader(x0: Float, y0: Float, x1: Float, y1: Float): Shader {
return LinearGradient(x0, y0, x1, y1, Color.WHITE, Color.TRANSPARENT, Shader.TileMode.CLAMP)
}
}