Android Imageview将颜色过滤器设置为渐变
我有一个白色的图像,我想用渐变色。我不想生成一组每种颜色都有特定渐变的图像,而是希望用代码(而不是xml)来实现这一点 要更改图像的颜色,我使用Android Imageview将颜色过滤器设置为渐变,android,imageview,gradient,Android,Imageview,Gradient,我有一个白色的图像,我想用渐变色。我不想生成一组每种颜色都有特定渐变的图像,而是希望用代码(而不是xml)来实现这一点 要更改图像的颜色,我使用 imageView.setColorFilter(Color.GREEN); 这个很好用。但是我如何应用渐变色而不是纯色呢LinearGradient没有帮助,因为setColorFilter无法应用于着色器对象 编辑:这是我的图像: 这就是我想要的: 这就是我得到的: 您必须获取图像视图的位图,并使用着色器重新绘制相同的位图 public vo
imageView.setColorFilter(Color.GREEN);
这个很好用。但是我如何应用渐变色而不是纯色呢LinearGradient
没有帮助,因为setColorFilter无法应用于着色器
对象
编辑:这是我的图像:
这就是我想要的:
这就是我得到的:
您必须获取
图像视图的位图
,并使用着色器重新绘制相同的位图
public void clickButton(View v){
Bitmap myBitmap = ((BitmapDrawable)myImageView.getDrawable()).getBitmap();
Bitmap newBitmap = addGradient(myBitmap);
myImageView.setImageDrawable(new BitmapDrawable(getResources(), newBitmap));
}
public Bitmap addGradient(Bitmap originalBitmap) {
int width = originalBitmap.getWidth();
int height = originalBitmap.getHeight();
Bitmap updatedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(updatedBitmap);
canvas.drawBitmap(originalBitmap, 0, 0, null);
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, 0, 0, height, 0xFFF0D252, 0xFFF07305, Shader.TileMode.CLAMP);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawRect(0, 0, width, height, paint);
return updatedBitmap;
}
更新3
我改变了:渐变色、LinearGradient width=0和PorterDuffXfermode。
下面是一幅了解PorterDuffXfermode的好图片:
您可以使用选择器
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
要动态定义和使用选择器,请参阅以下链接:
创建一个XML文件,并将其放在可绘制文件夹中
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"
/>
您是否首先使用xml格式的ImageView来绘制图像?@SQLiteNoob否,我正在代码中动态创建它们。不过这是用于应用背景的。我需要一些改变图像本身的东西。如何将其用于imageview?@故障对您有用吗?这不起作用-渐变设置为矩形,而不是形状本身。@故障,您的问题是imageview中的白色图像而不是形状。你是什么形状的?你必须在ImageView中检测一个形状吗?确切地说,我有一个白色的图像,我想用渐变来着色。我得到的是沿imageView的整个宽度和高度(其矩形)的梯度,而不是图像本身。