android:shape="rectangle" >
android:startColor="@android:color/black"
android:centerColor="@android:color/transparent"
android:endColor="@android:color/black"
android:angle="90"/>
渲染的渐变如下所示:
如您所见,黑色部分扩散到大部分屏幕.我希望黑色仅显示在顶部和底部的一小部分上.有没有办法让透明中心变大,或者让顶部和底部的黑色条纹变小?
我尝试使用链接的GradientDrawable文档中提到的一些其他XML属性,但它们似乎没有任何结果.
解决方法:
以下是使用自定义Drawable完成的方法.您可以根据需要调整LinearGradient,然后使用view.setBackground(new CustomDrawable());将其设置为视图的背景.
public class CustomDrawable extends Drawable {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int[] colors;
private float[] positions;
public CustomDrawable() {
paint.setStyle(Paint.Style.FILL);
this.colors = new int[]{0xff000000, 0xffaaaaaa, 0xffffffff, 0xffaaaaaa, 0xff000000};
this.positions = new float[]{.0f, .2f, .5f, .8f, 1.f};
}
@Override
public void setBounds(int left, int top, int right, int bottom) {
super.setBounds(left, top, right, bottom);
LinearGradient linearGradient = new LinearGradient(left, top,left, bottom, colors, positions, Shader.TileMode.CLAMP);
paint.setShader(linearGradient);
}
@Override
public void draw(@NonNull Canvas canvas) {
canvas.drawRect(getBounds(), paint);
}
@Override
public void setAlpha(@IntRange(from = 0, to = 255) int alpha) {
paint.setAlpha(alpha);
}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
paint.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSPARENT;
}
}
标签:android,xml,gradient,android-drawable
来源: https://codeday.me/bug/20190608/1197481.html