如何以编程方式创建带有拐角半径的波纹?

时间:2018-11-15 11:11:41

标签: android-layout ripple android-background rippledrawable

还有一些类似的问题。但是他们没有解决!

Set RippleDrawable corner radius programmatically

我知道可以using xml file完成此行为。但我必须以编程方式进行操作。

我的代码如下:

    GradientDrawable gd = new GradientDrawable();
    gd.setColor(Color.YELLOW);
    gd.setStroke(2, Color.RED);
    gd.setCornerRadius(45.0f);
    view.setBackground(gd);

    int[] colors = new int[]{Color.GRAY};
    int[][] states = new int[][]{ new int[]{}};
    ColorStateList stateList = new ColorStateList(states, colors);

    Drawable mask = getResources().getDrawable(R.drawable.icon1);
    RippleDrawable rippleDrawableBackgorund = new RippleDrawable(stateList, view.getBackground(), mask);

    view.setBackground(rippleDrawableBackgorund);

以下是处于按下状态的屏幕截图:

enter image description here

如何为RippleDrawable设置borderRadius?另外,rippleDrawableBackgorund.setRadius将此效果更改为悬停状态。

enter image description here

1 个答案:

答案 0 :(得分:0)

本指南可节省我的时间:) http://blog.blundellapps.co.uk/tut-programmatically-create-a-rippledrawable-of-any-color/

使用RippleDrawable构造函数的mask参数。

private static Drawable getRippleColor(int color) {
    float[] outerRadii = new float[8];
    Arrays.fill(outerRadii, 3);
    RoundRectShape r = new RoundRectShape(outerRadii, null, null);
    ShapeDrawable shapeDrawable = new ShapeDrawable(r);
    shapeDrawable.getPaint().setColor(color);
    return shapeDrawable;
}