为什么LinearGradient构造函数的此参数似乎不起作用? [英] Why doesn't this argument of the LinearGradient constructor seem to work?

查看:108
本文介绍了为什么LinearGradient构造函数的此参数似乎不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将具有线性渐变的自定义可绘制对象设置为我的SeekBar中条的背景可绘制对象.我在以下代码段的第二条语句中创建LinearGradient,并这样做:

I want to set a custom drawable with a linear gradient as the background drawable of the bar in my SeekBar. I am creating the LinearGradient in the second statement in the following snippet, and doing it like so:

// Creating the drawable:
ShapeDrawable shapeDrawable = new ShapeDrawable(new RectShape());
Shader linearGradientShader = new LinearGradient(0, 0, 300, 20, new int[] { Color.RED, Color.BLUE },
new float[] { 0, 1 }, Shader.TileMode.CLAMP);
shapeDrawable.getPaint().setShader(linearGradientShader);
shapeDrawable.setBounds(10, 10, 300, 30);

seekBar.setProgressDrawable(shapeDrawable);

这里的问题是,根据 规范 ,第6个参数定义为

The problem here is that, according to the specification, the 6th parameter is defined as

可能为空.颜色数组中每种相应颜色的相对位置[0..1].如果为null,则颜色会沿着渐变线均匀分布.

May be null. The relative positions [0..1] of each corresponding color in the colors array. If this is null, the the colors are distributed evenly along the gradient line.

我希望红色和蓝色都均匀分布,即一半的形状应偏红色,一半的颜色应偏蓝色(如下图所示).

I wanted both the red and blue colors to be distributed evenly, i.e. half the shape should appear redish and half should appear bluish (like the following image).

所以我尝试了nullnew float[] {0, 0.5f}new float[] {0, 1}作为第6个参数的值.我分别得到以下三个结果.

So I tried null, new float[] {0, 0.5f}, and new float[] {0, 1} as values of the 6th argument. I got the following three results respectively.

  1. 对于null:

对于new float[] {0, 0.5f}:

对于new float[] {0, 1}:

显示我要去哪里错了?我该如何解决?

推荐答案

使用

ShapeDrawable#setShaderFactory(ShapeDrawable.ShaderFactory工厂)

ShapeDrawable#setShaderFactory(ShapeDrawable.ShaderFactory factory)

工厂有一个方法Shader resize(int width, int height),每次您的可绘制范围更改时都会调用该方法,在这里您应该根据width/height参数返回您的LinearGradient着色器

the factory has a method Shader resize(int width, int height) which is called every time your drawable bounds change and this is a place where you should return your LinearGradient shader based on width / height parameters

您将看到,现在只需传递null positions,颜色就会均匀分布

as you will see you can now just pass null positions and colors will be distributed evenly

这篇关于为什么LinearGradient构造函数的此参数似乎不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆