更改位图背景颜色

问题描述

我正在使用必须使用此库https://github.com/divyanshub024/ColorSeekBar更改图像颜色的Android应用程序,我面临的问题是设置图像背景颜色时,它仅更改边框。我有一个Imageview,它已从字节数组转换为位图,并设置为ImageView

 <ImageView
    android:id="@+id/img_bitmap1"
    android:layout_width="match_parent"
    android:layout_height="@dimen/_300sdp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="@dimen/_10sdp"
    android:layout_marginStart="@dimen/_10sdp"
    android:layout_marginEnd="@dimen/_10sdp"
    />

我如何将字节数组转换为位图并将其设置为ImageView

val byteArray = intent.getByteArrayExtra("pictures")
    val bmp = BitmapFactory.decodeByteArray(byteArray,byteArray.size)
    img_bitmap1.setimageBitmap(bmp)

我如何改变颜色

 val imageview = requireActivity()!!.findViewById<View>(R.id.img_bitmap1) as ImageView

    color_seek_bar.setonColorchangelistener(object : ColorSeekBar.OnColorchangelistener {
        override fun onColorchangelistener(color: Int) {
            imageview.setBackgroundColor(color)
        }
    })

解决方法

问题是什么显示了您的ImageView,其中包含val bmp的设置。您的搜寻栏正在正确更改背景,并且您只能看到边框已更改,因为图像的“中心”(几乎整个)被bitmap

覆盖了

尝试不将val bmp加载到ImageView中,并检查整个背景(不仅是帧)是否在改变

,

通过获取像素值来更改Imageview颜色,并且仅更改颜色的像素而不是白色,可以解决问题。 通过此方法获得此成就。

 var bitmap = (imageviewgradient.drawable as BitmapDrawable).bitmap
            var newBitmap = replaceColor(bitmap,color)

上面的代码将图像转换为位图

    private fun replaceColor(src: Bitmap?,targetColor: Int): Bitmap? {
    if (src == null) {
        return null
    }
    // Source image size
    val width = src.width
    val height = src.height
    val pixels = IntArray(width * height)
    //get pixels
    src.getPixels(pixels,width,height)
    for (x in pixels.indices) {
        if(pixels[x]!=-1) {
            pixels[x] = targetColor
        }
    }
    // create result bitmap output
    val result = Bitmap.createBitmap(width,height,src.config)
    //set pixels
    result.setPixels(pixels,height)
    return result
}

仅通过简单的条件即完成主要工作

if(pixels[x]!=-1) {
            pixels[x] = targetColor
        }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...