I am having a problem with filling a ShapeDrawable containing a custom PathShape using the drawable’s setShaderFactory() method. The following code works perfectly when drawing a RectShape:
ShapeDrawable shape = new ShapeDrawable();
shape.setShape(new RectShape());
shape.setShaderFactory(new ShaderFactory() {
@Override
public Shader resize(int width, int height) {
LinearGradient gradient = new LinearGradient (0, 0,
width, height, Color.Red, Color.Blue,
TileMode.REPEAT);
return gradient;
}
});
When I change the RectShape to any custom PathShape, however, the drawable fills the entire shape with the gradient start color (red) only. In other words, the custom shapes draw correctly but the color is completely wrong. Has anyone seen this before and know what might be the problem?
After experimenting I found that the size of the gradient must be related to the standard width and standard height of the
PathShape, when it is created and has nothing to do with the height and width of theShapeDrawable. This means you must keep track of the standard width / height you assign to yourPathShapefor the entire life of theShapeDrawablein the event it is ever resized.Though somewhat inelegant, here is a solution: