问题描述
我正在使用必须使用此库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
}