更改位图背景颜色

时间:2020-10-26 10:47:17

标签: xml android-studio android-layout android-fragments android-styles

我正在使用必须使用此库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, 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)
        }
    })

2 个答案:

答案 0 :(得分:1)

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

覆盖了

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

答案 1 :(得分:0)

通过获取像素值来更改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
        }
相关问题