在 ImageView Android 上绘制时绘制的矩形不是正方形

时间:2021-02-03 21:31:53

标签: android imageview

我正在尝试在 ImageView 中的图像顶部绘制一个矩形。如果我将 (top, left) 指定为 (100, 100)(bottom, right) = (200, 200),我会得到:

enter image description here

如您所见,它不是正方形。我如何得到它?

绘制代码如下:

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)
    }

和xml文件:

<?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>

1 个答案:

答案 0 :(得分:1)

问题是您正在为 ImageView 使用 ImageView.background 属性和“match_parent”。 并且父级具有矩形形状,您使用它来获取新位图和画布的宽度和高度,因此 ImageView 也被拉伸。 如果您将 ImageView 的宽度和高度更改为“wrap_content”或特定大小,它将为您提供正方形。 如果使用 setImageBitmap 而不是“background”,效果会更好。

例如换行

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

image_view.setImageBitmap( tempBitmap)