El_Loco
El_Loco

Reputation: 1866

Drawn rectangle is not square when drawing on ImageView Android

I am trying to draw a rectangle on top of an image in an ImageView. If I specifify (top, left) as (100, 100) and (bottom, right) = (200, 200) I get this:

enter image description here

As you can see it is not a square. How do I get that?

Here is the code for drawing:

private fun drawRectangle(
        color: Int,
        bitmap: Bitmap
    ) {
        var image_view: ImageView = findViewById(R.id.image)
        val tempBitmap =
            Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888)

        var canvas: Canvas = Canvas(tempBitmap)

        val matrix: Matrix = Matrix()
        val bitmap_paint: Paint = Paint(Color.TRANSPARENT)
        canvas.drawBitmap(bitmap, matrix, bitmap_paint)
        var shapeDrawable: ShapeDrawable

        // rectangle positions
        var left = 100
        var top = 100
        var right = 200
        var bottom = 200

        // draw rectangle shape to canvas
        shapeDrawable = ShapeDrawable(RectShape())
        shapeDrawable.setBounds( left, top, right, bottom)
        shapeDrawable.getPaint().setColor(color)
        shapeDrawable.getPaint().setStyle(Paint.Style.STROKE)
        shapeDrawable.draw(canvas)

        image_view.background = BitmapDrawable(getResources(), tempBitmap)
    }

and the xml file:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitCenter" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:textSize="18sp"
        android:background="#80000000"
        android:textColor="@android:color/white" />

</FrameLayout>

Upvotes: 0

Views: 236

Answers (1)

van_izem
van_izem

Reputation: 66

The problem is that you are using ImageView.background property and "match_parent" for your ImageView. And parent have rectangular shape which you are using to get width and height for your new bitmap and canvas so ImageView also being stretched. If you change ImageView width and height to "wrap_content" or to specific size it will give you square square. Better results will be achieved if you use setImageBitmap instead of "background.

eg change line

image_view.background = BitmapDrawable(getResources(), tempBitmap)

to

image_view.setImageBitmap( tempBitmap)

Upvotes: 1

Related Questions