Skip to content

Custom Accent

Masayuki Hayashi edited this page Nov 22, 2016 · 4 revisions

Tutorial on how to make a custom accent

Purpose

Each DayView can be decorated by adding Accent object to it. Currently, we only provide the very basic DotAccent class as the one to add circled accents. Depending on how you want to depict the decoration, you may implement your own Custom Accent class to realize the decoration. In this tutorial, we will create a custom decoration that draws a line, instead of a circle, in a DayView.

How to do it

Create a class that extends Accent.

class LineAccent(length: Int, key: Any = Any()) : Accent(key) {
    override val width: Int = length
    override val height: Int = 1
    override val marginLeftRight: Int = 0
    override val marginTopBottom: Int = 0

    override fun draw(canvas: Canvas, x: Float, y: Float, paint: Paint) {
        // remember the current paint settings
        val oldColor = paint.color
        val oldStrokeWidth = paint.strokeWidth

        // modify the paint settings
        paint.color = Color.parseColor("#ff0000")
        paint.strokeWidth = height.toFloat()

        // draw a line
        canvas.drawLine(x - width / 2f, y, x + width / 2f, y, paint)

        // restore the previous paint settings
        paint.color = oldColor
        paint.strokeWidth = oldStrokeWidth
    }
}

All you have to do is to determine the width, height, and the horizontal and vertical margins, and then implement draw(canvas: Canvas, x: Float, y: Float, paint: Paint) method. Here, x and y represents the center location on canvas where the accent should be drawn. Also, note the paint object are recycled all through the accents you added to DayViews. So you should always save specific properties of the paint right before the actual drawing and restore them after performing the drawing to avoid mistakenly overwriting properties.

Use the implemented Accent class to decorate each day.

Result

When implemented like the one above, you should see the custom accent resulting like this:

UML

Clone this wiki locally