更改位图背景颜色

Change Bitmap Background Color

我正在开发 Android 必须使用此库更改图像颜色的应用程序 https://github.com/divyanshub024/ColorSeekBar,我面临的问题是设置图像背景颜色时,它只会更改边框。我有一个 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, 0, 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, 0, width, 0, 0, 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, 0, width, 0, 0, width, height)
    return result
}

主要工作只是通过一个简单的条件完成,即

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