首先在可绘制文件夹中创建一个渐变xml文件:
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle"
xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:startColor="#000" android:angle="90"/>
</shape>
对于API 23及更高版本:在定义了ImageView的布局中,只需添加属性android:foreground = "@drawable/gradient"
。这只是将渐变放置在ImageView的顶部。
简单但不建议使用您可以在显示图像的顶部添加另一个ImageView。然后,放在顶部的ImageView将设置android:src = "@drawable/gradient"
属性集。这确实有效,但我不建议这样做。是的,这很简单,但是使用ViewOverlay(我们将在下一个解决方案中看到)效率更高。
否则这里变得越来越复杂。首先,您必须使用addOnGlobalLayoutListener注册一个ViewTreeObserver并实现方法OnGlobalLayout。然后,您只需获取渐变可绘制对象并应用ImageView的边界(将成为ImageView的父对象)。最后,将drawable设置为ImageView的ViewOverlay。
老实说,我认为写这篇文章就足够了,但是我意识到这确实很复杂。所以这是它的ugly Kotlin版本:
ivImage.viewTreeObserver.addOnGlobalLayoutListener {
val drawable = resources.getDrawable(R.drawable.gradient).apply {
bounds = Rect(0, 0, ivImage.width, ivImage.height)
}
ivImage.overlay.add(drawable)
}
这将是Java版本(也不是漂亮的代码):
imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Drawable drawable = ContextCompat.getDrawable(context, R.drawable.gradient);
drawable.setBounds(0, 0, imageView.getWidth(), imageView.getHeight());
imageView.getOverlay().add(drawable);
}
});
重要提示:请勿伪造注销您的OnGlobalLayoutListener。可以在Java中的onGlobalLayout方法内完成此操作,如下所示:imageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
您的操作方式是使用FrameLayout(Frame Layout可帮助您将一个布局放置在另一个布局上)。首先在框架布局中,放置ImageView,然后放置一个普通的View,背景为gradient_transparent_black.xml(因此,基本上,该视图位于ImageView上方)。
以下是示例:(您可以根据需要将View height设置为80dp)
<FrameLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toOf="@+id/imageView3"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/image_you_want" />
<View
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_gravity="bottom"
android:background="@drawable/gradient_transparent_black"
android:clickable="false" />
</FrameLayout>
gradient_transparent_black.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:startColor="#000000"
android:endColor="#00FFFFFF"
android:angle="90"
android:dither="true"
/>
</shape>