我有一张白色图像,我想用渐变色。我不想生成一堆图像,每个图像都使用特定的渐变色,我想在代码(而不是xml)中执行此操作。Imageview将颜色过滤器设置为渐变
更改图像的颜色,我用
imageView.setColorFilter(Color.GREEN);
这工作得很好。但是,如何应用渐变色而不是纯色? LinearGradient
没有帮助,因为setColorFilter不能应用于Shader
对象。
编辑:这是我的形象:
这就是我想要的:
而这就是我得到:
我有一张白色图像,我想用渐变色。我不想生成一堆图像,每个图像都使用特定的渐变色,我想在代码(而不是xml)中执行此操作。Imageview将颜色过滤器设置为渐变
更改图像的颜色,我用
imageView.setColorFilter(Color.GREEN);
这工作得很好。但是,如何应用渐变色而不是纯色? LinearGradient
没有帮助,因为setColorFilter不能应用于Shader
对象。
编辑:这是我的形象:
这就是我想要的:
而这就是我得到:
你必须让你的ImageView
的Bitmap
和重绘相同Bitmap
与Shader
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 = 0和PorterDuffXfermode的颜色。 这里好的图片来了解PorterDuffXfermode:
这如何与imageview一起使用? – Malfunction
@Malfunction,对不起,我更新了我的答案 – LaurentY
@Malfunction我更新了我的答案,我测试了它 – LaurentY
你可以使用一个选择
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
这是为了应用背景。我需要改变图像本身的东西。 – Malfunction
创建一个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在XML画摆在首位的图像添加到您的图像视图
<ImageView
android:id="@+id/umageview1"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/gradient"
android:layout_centerHorizontal="true"
/>
? – SQLiteNoob
@SQLiteNoob不,我正在代码中动态创建它们。 – Malfunction