preface

When you customize a View, you will sometimes encounter some requirements like track movement, such as moving an object along a specific route. Usually, Path and PathMeasure are used to achieve this, such as the following renderings

It looks interesting, but in fact, it is very simple in nature, that is, the boat moves along a given route, the route is Path, and then the PathMeasure is used to calculate parameters related to Path. This article will talk about PathMeasure, not BB, but the code first

PS: ACTUALLY, I want to post PathMeasure API first, but I feel that this article is too long, so I will directly put the link

Official document of PathMeasure

Chinese PathMeasure API

GetLength (), getPosTan(float Distance, float[] pos, float[] tan), getMatrix(float Distance, Matrix Matrix, Int flags), which the following code will use

        mMatrix.reset()
        pathMeasure = PathMeasure(path, false)
        length = pathMeasure.length

        /* * Since the path is irregular, in order to keep the boat close to the path as it moves, we need to move the boat and rotate it at an Angle * to do this, there are two ways */

        /* / (boatDx, pos, tan) (boatDx, pos, tan) (boatDx, pos, tan) Float = ((math.atan2 (tan[1].todouble (), tan[0].todouble ())*180f/ math.pi).tofloat ()) // rotate mMatrix. PostRotate (degrees, degrees) PostTranslate ((pos[0]-bitmap.width/2F).tofloat (), (pos[1]-bitmap.height).toFloat()) */

        // Use the API
        //getMatrix(), get the Matrix at the specified Path position
        pathMeasure.getMatrix(boatDx, mMatrix, PathMeasure.TANGENT_MATRIX_FLAG
                or PathMeasure.POSITION_MATRIX_FLAG)
        mMatrix.preTranslate((-bitmap.width / 2).toFloat(), (-bitmap.height).toFloat())
        canvas.drawPath(path, paint)
        canvas.drawBitmap(bitmap, mMatrix, paint)

        circleMatrix.reset()
        circlePathMeasure = PathMeasure(circlePath, false)
        circleLength = circlePathMeasure.length
        circlePathMeasure.getMatrix(circleDx, circleMatrix, PathMeasure.TANGENT_MATRIX_FLAG
                or PathMeasure.POSITION_MATRIX_FLAG)
        circleMatrix.preTranslate((-bitmap.width / 2).toFloat(), (-bitmap.height).toFloat())
        canvas.drawPath(circlePath, paint)
        canvas.drawBitmap(bitmap, circleMatrix, paint)
Copy the code

PostTranslate (); preTranslate(); postTranslate(); preTranslate()

Complete project code