first post here. Also excuse me in case any of this is glaringly obvious. I am a total newbie at xml & java and mainly a designer.
I want to implement the design I created in Adobe Illustrator and Photoshop for an app I am working on. I know you can use XML with start/center/end color for basic gradients. But I want to create exactly the one I designed, with as many colors as desired and custom intervals where they start and end. I found this solution in another thread:
ShapeDrawable.ShaderFactory shaderFactory = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
LinearGradient linearGradient = new LinearGradient(0, 0, width, height,
new int[] {
0xFF1e5799,
0xFF207cca,
0xFF2989d8,
0xFF207cca }, //substitute the correct colors for these
new float[] {
0, 0.40f, 0.60f, 1 },
Shader.TileMode.REPEAT);
return linearGradient;
}
};
PaintDrawable paint = new PaintDrawable();
paint.setShape(new RectShape());
paint.setShaderFactory(shaderFactory);
How do I include colors I manually defined via values/colors? It doesn’t let me use @color/darkgrey etc. obviously, as they are not integer. Also I cannot put them in in hexa-code for probably the same reason.
I’d like to do new int [] {@color/A, @color/B, …}
Also, second question: the float seems to define the custom intervals from which the colors are used. In his example he had 4 int colors, and 4 float values – but that would only define 3 intervals from what I understand (?):
[0,0.4] [0.4,0.6] [0.6,1] in percentages.
Or does it work in a different way?
I’ll specify further details, if neccessary.
2
Answers
If you want to use color resource values in java, you will need access to a
Context
object or one of its subclasses (likeActivity
). Then you can callNot exactly. The
float[]
values define the point from0
to1
where each color is placed. So if you have four colors, you’ll want four positions (and the first and last should be 0 and 1).With that in mind, you could write something like this:
This would produce a gradient from:
color_one
tocolor_two
at0
to0.33
color_two
tocolor_three
at0.33
to0.67
color_three
tocolor_four
at0.67
to1
.@Ben’s answer is complete and answers most of your questions. To answer also the last point
In Java you prepend ‘0x’ to indicate an hexa notation. Colors are expressed as ARGB (Alpha/R/G/B), so the expressions
are correct.