Android - How can I zoom in on a custom View I made using Kotlin?

Viewed 50

I have a FloorView, and within this FloorView I'll be filling it with RoomViews. Every floor has rooms. I want a functionality that can allow the user to zoom in on the floor, and see the rooms up closer. Think of it as Google maps. The earth is the floor, and the buildings/road are the rooms

The floor is huge, will have many rooms, that's why I want the ability to zoom in. How can I achieve this? I want the zoom functionality to be the exact same from Google maps; using two fingers

I have already built a FloorView, and a RoomView. I have tried Googling, and spotted a library that allows zooms for an ImageView, which is not what I need. I'm at a loss, I cannot find other sources

Here's my code

FloorView.kt

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

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.FILL_AND_STROKE
        color = Color.RED
    }

    private val screenHeight = context.resources.displayMetrics.heightPixels
    private val screenWidth = context.resources.displayMetrics.widthPixels

    private val rectangle = RectF(screenWidth.toFloat(), screenHeight.toFloat(), 0f, 0f)

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas!!.drawRect(rectangle, paint)
    }

}

RoomView.kt

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

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.FILL_AND_STROKE
        color = Color.CYAN
    }


    private val rectangle = RectF(1000f, 1000f, 0f, 0f)

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas!!.drawRect(rectangle, paint)
    }

}

Thank you for helping me

1 Answers

This is a big topic, but lets break it down a lit and give you some pointers on further research.

First off you need to detect the zoom/scale gesture (two finger pinch), for that you you can use the ScaleGestureDetector class, you can also do it yourself by analysing the motion events. Along with zooming you probably want to handle panning as well so you can move the zoomed area around.

To understand this you need to understand how Android handles MotionEvents, this is a good article to begin with.

Second you need to understand how to draw things at different scales and positions, there are two ways to handle this, you can draw things yourself at different positions and sizes by adjusting the coordinates of items you draw or you can use the canvas build in methods to scale and translate(pan) what you have already drawn.

While you can use the canvas scale and translate methods these are just shortcuts to using a Matrix on a canvas to map how objects are drawn on the canvas to how they are displayed on screen.

The article gives some more detail on using a canvas Matrix

Related