Imageview将滤镜设置为渐变

时间:2016-06-12 14:59:30

标签: android imageview gradient

我有一张白色图片,我想用渐变色。我想在代码(而不是xml)中执行此操作,而不是生成一堆每个都用特定渐变着色的图像。

要更改图像的颜色,我使用

imageView.setColorFilter(Color.GREEN);

这很好用。但是,如何应用渐变色而不是纯色? LinearGradient无效,因为setColorFilter无法应用于Shader个对象。

编辑:这是我的图片:

enter image description here

这就是我想要的:

enter image description here

这就是我得到的:

enter image description here

3 个答案:

答案 0 :(得分:34)

您必须获得Bitmap的{​​{1}}并使用ImageView重绘Bitmap

Shader

更新3 我更改了:渐变颜色,LinearGradient width = 0和PorterDuffXfermode。 这里有一个了解PorterDuffXfermode的好照片: enter image description here

答案 1 :(得分:-1)

您可以使用选择器

main_header.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout         xmlns:android="http://schemas.android.com/apk/res/.    android"
    android:layout_width="fill_parent"
    android:layout_height="50dip"
    android:orientation="horizontal"
    android:background="@drawable/main_header_selector"> 
</LinearLayout>

main_header_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector     xmlns:android="http://schemas.android.com/apk/res/.     android">
<item>
    <shape>
        <gradient
        android:angle="90"
        android:startColor="#FFFF0000"
        android:endColor="#FF00FF00"
        android:type="linear" />
    </shape>
</item>
</selector>

可以将相同的背景应用于ImageView。

要动态定义和使用选择器,请参阅以下链接: Dynamically defining and using selectors

答案 2 :(得分:-1)

创建一个XML文件,并将其放在drawable文件夹中。

<强> gradient.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
    android:startColor="#CCb1e7fa"
    android:centerColor="#B3ffffff"
    android:endColor="#CCb1e7fa"
    android:angle="180" />
<corners android:radius="5dp" />

</shape>

接下来将其添加为图像视图的背景

    <ImageView
            android:id="@+id/umageview1"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:background="@drawable/gradient"
            android:layout_centerHorizontal="true"
            />
相关问题