경로를 따라 그리는 Path Animation

|

먼저 View를 상속받는 캔버스(Canvas)를 가진 클래스를 하나 구현합니다. 그리고 setPercentage 메소드를 만들어줍니다. 클래스 외부에서 애니메이션을 동작시킬 때 필요한 progress 관련 메소드입니다.

class PathView(context: Context, attrs: AttributeSet) : View(context, attrs) {

    companion object {
        private const val CORNER_ROUND = 40F
    }

    private val wayPointList = ArrayList<PointF>()

    private val paint = Paint()

    private var progress = 0F
    private var pathLength = 0F

    init {
        paint.apply {
            color = context.getColor(R.color.path_color)
            style = Paint.Style.STROKE
            isAntiAlias = true
            strokeWidth = 8.0F
            strokeCap = Paint.Cap.ROUND
            strokeJoin = Paint.Join.ROUND
        }

        initDummyData()
    }

    private fun initDummyData() {
        wayPointList.add(PointF(190F, 1715F))
        wayPointList.add(PointF(270F, 1715F))
        wayPointList.add(PointF(270F, 650F))
        wayPointList.add(PointF(460F, 650F))
        wayPointList.add(PointF(460F, 500F))
    }

    fun setPath(pointList: ArrayList<Point>) {
        wayPointList.clear()

        for (p in pointList) {
            val x = MapCoordinateConverter.getCanvasXFromWorldX(p.x).toFloat()
            val y = MapCoordinateConverter.getCanvasXFromWorldX(p.y).toFloat()

            wayPointList.add(PointF(x, y))
        }

        invalidate()
    }

    fun setPercentage(percentage: Float) {
        if (percentage < 0.0f || percentage > 1.0f) {
            throw IllegalArgumentException("setPercentage not between 0.0f and 1.0f")
        }

        progress = percentage
        invalidate()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        drawPath(canvas)
    }

    private fun drawPath(canvas: Canvas?) {
        val p = createPath()

        val measure = PathMeasure(p, false)
        pathLength = measure.length

        val total = pathLength - pathLength * progress
        val pathEffect = DashPathEffect(floatArrayOf(pathLength, pathLength), total)

        val cornerPathEffect = CornerPathEffect(CORNER_ROUND)
        paint.pathEffect = ComposePathEffect(cornerPathEffect, pathEffect)

        canvas?.drawPath(p, paint)
    }

    private fun createPath(): Path {
        val p = Path()

        if(wayPointList.size > 0) {
            p.moveTo(wayPointList[0].x, wayPointList[0].y)
            for (pf in wayPointList) {
                p.lineTo(pf.x, pf.y)
            }
        }

        return p
    }

}

위에서 만든 클래스를 외부에서 사용할 때는 다음과 같이 작성하면 됩니다.

class MapView(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {

    private val pathView = PathView(context, attrs)

    init {

        val layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT)

        addView(pathView, layoutParams)
    }

    fun start() {
        playPathAnimation(pathView)
    }

    fun setPath(pointList: ArrayList<Point>) {
        pathView.setPath(pointList)
    }

    private fun playPathAnimation(target: View) {
        val anim = ObjectAnimator.ofFloat(target, "percentage", 0.0f, 1.0f)

        anim.duration = 3000
        anim.interpolator = LinearInterpolator()
        anim.start()
    }
}

TextView의 Width를 Programatically하게 얻기

|

TextView에 Text가 렌더링되기 전에 미리 width를 얻는 코드입니다. Text의 width는 TextView에서 출력되는 폰트의 종류와 크기 등에 영향을 받기 때문에, TextView의 현재 Paint() 정보를 가져와서 계산을 해줍니다.

textView.setText(texxt);
int width = (int)textView.getPaint().measureText(text);

다양한 Animation 샘플(Scene Transition)

|
package com.snowdeer.animation.sample.fragment

import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.transition.*
import com.snowdeer.animation.sample.R
import kotlinx.android.synthetic.main.fragment_scene_change.view.*
import kotlinx.android.synthetic.main.scene1.view.*

class SceneChangeFragment :Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {

        val view = inflater.inflate(R.layout.fragment_scene_change, container, false)

        val scene1 = Scene(view.scene_root!!, view.container)
        val scene2 = Scene.getSceneForLayout(view.scene_root, R.layout.scene2, activity!!)
        val scene3 = Scene.getSceneForLayout(view.scene_root, R.layout.scene3, activity!!)


        view.scene_1_button.setOnClickListener {
            TransitionManager.go(scene1)
        }

        view.scene_2_button.setOnClickListener {
            val set = TransitionSet()
            val slide = Slide(Gravity.LEFT)
            slide.addTarget(R.id.image2)
            set.addTransition(slide)
            set.addTransition(ChangeBounds())
            set.ordering = TransitionSet.ORDERING_TOGETHER
            set.duration = 350
            TransitionManager.go(scene2, set)
        }

        view.scene_3_button.setOnClickListener {
            TransitionManager.go(scene3)
        }

        return view
    }
}

다양한 Animation 샘플(룰렛, Roulette)

|

PieChartView.kt

package com.snowdeer.animation.sample.component

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import kotlin.math.cos
import kotlin.math.sin

data class ValueItem(var name: String, var value: Float, var color: Int)

class PieChartView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {

    private val WIDTH = 800
    private val HEIGHT = 800

    private var list = ArrayList<ValueItem>()

    fun setValueList(list: ArrayList<ValueItem>) {
        this.list = list
        invalidate()
    }

    override fun onDraw(canvas: Canvas?) {
        drawSlice(canvas)
        drawText(canvas)
    }

    private fun drawSlice(canvas: Canvas?) {
        val total = getTotalSize()
        val dAngle = 360.0F / total

        val centerX = measuredWidth / 2
        val centerY = measuredHeight / 2
        val left = centerX - WIDTH / 2
        val top = centerY - HEIGHT / 2
        val right = centerX + WIDTH / 2
        val bottom = centerY + HEIGHT / 2

        val rectF = RectF(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat())

        var fromAngle = 0.0F
        for (item in list) {
            val paint = Paint()
            paint.color = item.color

            val sweepAngle = item.value * dAngle
            val drawArc = canvas?.drawArc(rectF, fromAngle, sweepAngle, true, paint)

            fromAngle += sweepAngle
        }
    }

    private fun drawText(canvas: Canvas?) {
        val total = getTotalSize()
        val dAngle = 360.0F / total

        val centerX = measuredWidth / 2
        val centerY = measuredHeight / 2
        val left = centerX - WIDTH / 2
        val top = centerY - HEIGHT / 2
        val right = centerX + WIDTH / 2
        val bottom = centerY + HEIGHT / 2

        val rectF = RectF(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat())
        val rect = Rect(left, top, right, bottom)

        var fromAngle = 0.0F
        for (item in list) {
            val text = item.name
            val sweepAngle = item.value * dAngle
            val angle = (fromAngle + (sweepAngle / 2.0F)) * 0.0174532925F

            val paint = Paint()
            paint.color = Color.BLACK
            paint.textSize = 40F
            paint.textAlign = Paint.Align.CENTER

            canvas?.save()

            paint.getTextBounds(text, 0, text.length, rect)
            var x = rectF.centerX() + cos(angle) * (rectF.width() / 4 + rect.width() / 2)
            val y = rectF.centerY() + sin(angle) * (rectF.height() / 4 + rect.width() / 2)

            x -= rect.width() / 2
            canvas?.rotate(
                fromAngle + (sweepAngle / 2), (x + rect.exactCenterX()),
                (y + rect.exactCenterY())
            )
            canvas?.drawText(text, x, y, paint)
            canvas?.restore()

            fromAngle += sweepAngle
        }
    }

    private fun getTotalSize(): Float {
        var sum = 0.0F

        for (item in list) {
            sum += item.value
        }

        return sum
    }
}


RouletteFragment.kt

package com.snowdeer.animation.sample.fragment

import android.animation.ObjectAnimator
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.animation.doOnEnd
import androidx.fragment.app.Fragment
import com.snowdeer.animation.sample.R
import com.snowdeer.animation.sample.component.ValueItem
import kotlinx.android.synthetic.main.fragment_roulette.*
import android.view.animation.DecelerateInterpolator
import kotlinx.android.synthetic.main.fragment_roulette.view.*
import java.util.*
import kotlin.collections.ArrayList


class RouletteFragment : Fragment() {

    private var degree = 0
    private var isAnimating = false

    private val candidateList = arrayListOf(
        ValueItem("snowdeer", 1.0F, Color.parseColor("#FFDECF3F")),
        ValueItem("yang", 1.0F, Color.parseColor("#FFF17CB0")),
        ValueItem("down", 1.0F, Color.parseColor("#FF4D4D4D")),
        ValueItem("ran", 1.0F, Color.parseColor("#FFB2912F")),
        ValueItem("song", 1.0F, Color.parseColor("#FF00B200")),
        ValueItem("john", 1.0F, Color.parseColor("#FFFD4425"))
    )

    private var itemCount = 3

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val view = inflater.inflate(R.layout.fragment_roulette, container, false)

        view.piechart_view.setValueList(getList(itemCount))

        view.add_button.setOnClickListener {
            itemCount++
            if (itemCount >= candidateList.size) {
                itemCount = candidateList.size
            }
            view.piechart_view.setValueList(getList(itemCount))
        }

        view.remove_button.setOnClickListener {
            itemCount--
            if (itemCount <= 1) {
                itemCount = 1
            }
            view.piechart_view.setValueList(getList(itemCount))
        }

        view.rotate_button.setOnClickListener {
            rotate()
        }

        return view
    }

    private fun getList(count: Int): ArrayList<ValueItem> {
        val list = ArrayList<ValueItem>()
        for (i in 0 until count) {
            list.add(this.candidateList[i])
        }
        return list
    }


    private fun rotate() {
        val random= Random()
        if (!isAnimating) {
            isAnimating = true

            val targetDegree = degree + random.nextInt(360) * (random.nextInt(7) + 7)
            val rotateAnimator = ObjectAnimator.ofFloat(piechart_view,
                "rotation", degree.toFloat(), targetDegree.toFloat())
            rotateAnimator.interpolator = DecelerateInterpolator()
            rotateAnimator.duration = 3000
            rotateAnimator.doOnEnd {
                degree = targetDegree
                isAnimating = false
            }
            rotateAnimator.start()
        }
    }
}

Canvas에 Pie Chart 그리기

|
package com.snowdeer.animation.sample.component

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import kotlin.math.cos
import kotlin.math.sin

data class ValueItem(var name: String, var value: Float, var color: Int)

class PieChartView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {

    private val WIDTH = 800
    private val HEIGHT = 800

    private var list = ArrayList<ValueItem>()

    fun setValueList(list: ArrayList<ValueItem>) {
        this.list = list
        invalidate()
    }

    override fun onDraw(canvas: Canvas?) {
        drawSlice(canvas)
        drawText(canvas)
    }

    private fun drawSlice(canvas: Canvas?) {
        val total = getTotalSize()
        val dAngle = 360.0F / total

        val centerX = measuredWidth / 2
        val centerY = measuredHeight / 2
        val left = centerX - WIDTH / 2
        val top = centerY - HEIGHT / 2
        val right = centerX + WIDTH / 2
        val bottom = centerY + HEIGHT / 2

        val rectF = RectF(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat())

        var fromAngle = 0.0F
        for (item in list) {
            val paint = Paint()
            paint.color = item.color

            val sweepAngle = item.value * dAngle
            val drawArc = canvas?.drawArc(rectF, fromAngle, sweepAngle, true, paint)

            fromAngle += sweepAngle
        }
    }

    private fun drawText(canvas: Canvas?) {
        val total = getTotalSize()
        val dAngle = 360.0F / total

        val centerX = measuredWidth / 2
        val centerY = measuredHeight / 2
        val left = centerX - WIDTH / 2
        val top = centerY - HEIGHT / 2
        val right = centerX + WIDTH / 2
        val bottom = centerY + HEIGHT / 2

        val rectF = RectF(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat())
        val rect = Rect(left, top, right, bottom)

        var fromAngle = 0.0F
        for (item in list) {
            val text = item.name
            val sweepAngle = item.value * dAngle
            val angle = (fromAngle + (sweepAngle / 2.0F)) * 0.0174532925F

            val paint = Paint()
            paint.color = Color.BLACK
            paint.textSize = 40F
            paint.textAlign = Paint.Align.CENTER

            canvas?.save()

            paint.getTextBounds(text, 0, text.length, rect)
            var x = rectF.centerX() + cos(angle) * (rectF.width() / 4 + rect.width() / 2)
            val y = rectF.centerY() + sin(angle) * (rectF.height() / 4 + rect.width() / 2)

            x -= rect.width() / 2
            canvas?.rotate(
                fromAngle + (sweepAngle / 2), (x + rect.exactCenterX()),
                (y + rect.exactCenterY())
            )
            canvas?.drawText(text, x, y, paint)
            canvas?.restore()

            fromAngle += sweepAngle
        }
    }

    private fun getTotalSize(): Float {
        var sum = 0.0F

        for (item in list) {
            sum += item.value
        }

        return sum
    }
}