Custom View in Android

  1. Measuring stage: each view must measure itself.
  2. Layout stage: each ViewGroup finds the right position for its children on the screen by using the child size and also by following the layout rules.
  3. Drawing stage: after measuring and positioning all of the views, each view happily draws itself.
class EmotionalFaceView : View
  1. constructor(context: Context)
    To create a new View instance from Kotlin code, it needs the Activity context.
  2. constructor(context: Context, attrs: AttributeSet)
    To create a new View instance from XML.
  3. constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int)
    To create a new view instance from XML with a style from theme attribute.
  4. constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int)
    To create a new view instance from XML with a style from theme attribute and/or style resource.
<com.example.customui.EmotionalFaceView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/face_id"
app:layout_constraintTop_toBottomOf="parent"
app:layout_constraintLeft_toRightOf="parent"
app:layout_constraintRight_toLeftOf="parent"/>

Drawing on Canvas

At first, let’s prepare our colours for making the custom view.


private val paint = Paint(Paint.ANTI_ALIAS_FLAG)

private var faceColor = Color.YELLOW
private var eyesColor = Color.BLACK
private var mouthColor = Color.BLACK

private var size = 320
private val mouthPath = Path()
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)

drawFaceBackground(canvas)
drawEyes(canvas)
drawMouth(canvas)
}
private fun drawFaceBackground(canvas: Canvas?) {
paint.color = faceColor
paint.style = Paint.Style.FILL

val rad = size / 2f

canvas?.drawCircle(rad, rad, rad, paint)

}
private fun drawEyes(canvas: Canvas?) {
paint.color = mouthColor
paint.style = Paint.Style.FILL

val leftEyeRect = RectF(size * 0.25f, size * 0.25f, size * 0.40f, size * 0.5f)
canvas?.drawOval(leftEyeRect, paint)

val rightEyeRect = RectF(size * 0.60f, size * 0.25f, size * 0.75f, size * 0.5f)
canvas?.drawOval(rightEyeRect, paint)

}
private fun drawMouth(canvas: Canvas?) {
mouthPath.reset()

mouthPath.moveTo(size * 0.15f, size * 0.65f)
mouthPath.quadTo(size * 0.5f, size * 0.75f, size * 0.85f, size * 0.65f)
mouthPath.quadTo(size * 0.5f, size * 0.98f, size * 0.15f, size * 0.65f)
paint.color = mouthColor
paint.style = Paint.Style.FILL

canvas?.drawPath(mouthPath, paint)

}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store