首页 > 解决方案 > 在ImageView Android上绘制时绘制的矩形不是正方形

问题描述

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

在此处输入图像描述

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

这是绘图的代码:

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>

标签: androidimageview

解决方案


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

例如换线

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

image_view.setImageBitmap(tempBitmap)


推荐阅读