【发布时间】:2019-12-04 20:53:28
【问题描述】:
我有一个ImageView,我想对其进行模糊处理。我正在使用这种方法进行模糊:https://futurestud.io/tutorials/how-to-blur-images-efficiently-with-androids-renderscript
这是我的 ImageView 初始化的布局 XML 文件的一部分:
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/InfoConstraint"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/constraintLayout">
<ImageView
android:id="@+id/backdrop"
android:layout_width="0dp"
android:layout_height="0dp"
android:alpha="0.9"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@android:color/background_light" />
此约束布局也在另一个约束布局内。然后,我在带有 ID 的 custom view 中定位 backdrop 并提取 bitmap,这样我就可以使用上面链接中的代码来模糊 bitmap。这样做后,我将bitmap 转换回ImageView
backdrop = findViewById(R.id.backdrop);
Bitmap b = BitmapFactory.decodeResource(getResources(), R.id.backdrop);
Bitmap blurredBitmap = BlurBuilder.blur(context, b);
backdrop.setImageBitmap(blurredBitmap);
唯一的问题是当我调用BlurBuilder 时出现空指针异常。这是错误堆栈:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
at com.example.sapp.BlurBuilder.blur(BlurBuilder.java:15)
at views.customsapp$override.init(customsapp.java:73)
at views.customsapp$override.access$dispatch(Unknown Source:67)
at views.customsapp.init(Unknown Source:15)
at views.customsapp$override.init$body(customsapp.java:48)
at views.customsapp$override.access$dispatch(Unknown Source:132)
at views.customsapp.<init>(customsapp.java:46)
... 33 more
好像没有找到backdrop这里有什么问题?我想不明白。我敢打赌,当我从 ImageView 创建位图时,会发生一些我不知道的事情,因为背景显然在那里,因为我正在调用 findViewById(),这很有效。
更新
这是我尝试 Anjana 的答案时抛出的新异常
Caused by: java.lang.IllegalArgumentException: width and height must be > 0
at android.graphics.Bitmap.createBitmap(Bitmap.java:1113)
at android.graphics.Bitmap.createBitmap(Bitmap.java:1080)
at android.graphics.Bitmap.createBitmap(Bitmap.java:1030)
at android.graphics.Bitmap.createBitmap(Bitmap.java:991)
E/AndroidRuntime: at views.customsapp
.init(customsapp.java:78)
at views.customsapp.<init>(customsapp.java:48)
... 28 more
【问题讨论】:
标签: android bitmap imageview android-custom-view blur