Issue
I am working with Canvas in Android and the issue I am facing is during the screen rotation. Let's say I start the app in portrait mode and draw something on the canvas, then on rotation some part of the canvas moves out of the screen. See the screenshots attached.
Code snippets from my file where Canvas is implemented (I will provide other parts if they are required just let me know through comment) :
private lateinit var mBitmap: Bitmap
private lateinit var mCanvas: Canvas
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.apply {
drawColor(0)
drawBitmap(mBitmap, 0f, 0f, mBitmapPaint)
drawPath(mPath, mPaint)
}
}
private fun createBitmap(w: Int, h: Int) {
val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
mBitmap = bitmap
mCanvas = Canvas(bitmap)
clear()
}
private fun createBitmap() {
val p = displayDimensions
val bitmapSize = max(p.x,p.y)
createBitmap(bitmapSize, bitmapSize)
}
init {
mPaint = Paint()
mPaint.isAntiAlias = true
mPaint.isDither = true
mPaint.color = foregroundColor
mPaint.style = Paint.Style.STROKE
mPaint.strokeJoin = Paint.Join.ROUND
mPaint.strokeCap = Paint.Cap.ROUND
mPaint.strokeWidth = currentStrokeWidth.toFloat()
createBitmap()
}
Solution
Going through a couple of blogs and SO answers I finally found the answer on Android developers documentation - here
My code snippet looks like :
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
val scaledBitmap: Bitmap = Bitmap.createScaledBitmap(mBitmap, w, h, true)
}
mCanvas = Canvas(scaledBitmap)
}
This way you can handle the screen orientation when the device rotates. The createScaledBitmap()
function takes care of taking the previous drawn Bitmap and scaling it according to new width and height.
Answered By - oyeraghib
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.