Create a Custom View using Canvas Template
1 min readApr 28, 2020
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
class ShaderBackground : View {
private lateinit var paint: Paint /** The screen half width. */
private var screenHalfWidth = 0f /** The screen half height. */
private var screenHalfHeight = 0f
/** The screen width. */
private var screenWidth = 0f
/** The screen height. */
private var screenHeight = 0f
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
init()
}
private fun init() {
paint = Paint();
paint.strokeWidth = 10f;
paint.style = Paint.Style.FILL_AND_STROKE;
paint.isDither = true
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
screenWidth = MeasureSpec.getSize(widthMeasureSpec).toFloat()
screenHeight = MeasureSpec.getSize(heightMeasureSpec).toFloat()
screenHalfWidth = (screenWidth / 2)
screenHalfHeight = (screenHeight / 2)
setMeasuredDimension(screenWidth.toInt(), screenHeight.toInt())
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
@SuppressLint("DrawAllocation")
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
var gradient = RadialGradient(
panelHalfWidth,
topShaderCenterY,
panelWidth,
Color.BLUE, Color.BLACK,
Shader.TileMode.CLAMP
)
paint.shader = gradient //LEFT TOP
paint.color = Color.BLUE;
canvas!!.drawRect(0f, 0f, 200, 100, paint) //LEFT BOTTOM
paint.color = Color.BLUE;
canvas.drawRect(0f, screenHeight-200, 100, screenHeight, paint)
//RIGHT TOP
paint.color = Color.RED;
canvas!!.drawRect(screenwidth-200, 0f, screenWidth, screenHalfHeight, paint) //RIGHT BOTTOM
paint.color = Color.GREEN;
canvas.drawRect(screenwidth-200, screenHeight-200,screenwidth,screenHeight, paint)
}
}
The result will be 4 rectangles on 4 sides of the view