Search code examples
androidcanvasdrawing

Canvas rotate and drawbitmap


I have path rect and bitmap, want to add bitmap inside path, While draw on start it appears as expected, but while rotate and draw bitmap goes outside bounds. Here is my code.

canvas!!.rotate(rotateAngle.toFloat(), rectF2.centerX(), rectF2.centerY())
canvas!!.drawPath(path, mPaint)
bitmap?.let {
    canvas!!.drawBitmap(it, rectF2.left, rectF2.top, mPaint)
}
canvas!!.restore()

RotateAngle is 0

enter image description here

RotateAngle is 50

enter image description here


Solution

  • Here is the working solution with matrix.

    bitmap?.let {
        val rotate = Matrix()
        rotate.setRotate(rotateAngle.toFloat(), it.width / 2.0f, it.height / 2.0f)
        rotate.postTranslate((rectF2.centerX() - it.width / 2.0f), (rectF2.centerY() - it.height / 2.0f))
        canvas!!.drawBitmap(it, rotate, mPaint)
    }