Программно создать кнопку с градиентным ходом? - PullRequest
0 голосов
/ 16 мая 2018

Я работаю над созданием кнопки без заливки, но с градиентным штрихом. Для справки, вот конечный результат, который мне нужен:

enter image description here

Я хотел бы знать, как создать такую ​​кнопку с градиентным штрихом и без заливки программно. Я просмотрел класс GradientDrawable и метод setStroke() в нем. Никто, кажется, не позволяет этого. Есть ли способ программно выполнить это или это вообще невозможно?

Ответы [ 2 ]

0 голосов
/ 16 мая 2018

Я попробовал кое-что для вас .. Используйте mRect.set, чтобы установить путь, и mPath.addRoundRect, добавьте прямоугольник. Используйте setShader для цели штриховки ссылка

Класс рисования:

public class CustomDrawable extends Drawable {
Paint mPaint;
int startColor, endColor, mBorderWidth, mBorderRadius;
RectF mRect;
Path mPath;

public CustomDrawable(int startColor, int endColor, int borderWidth, int borderRadius) {
    mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mPaint.setStyle(Paint.Style.FILL);

    mPath = new Path();
    mPath.setFillType(Path.FillType.EVEN_ODD);

    mRect = new RectF();
    this.startColor = startColor;
    this.endColor = endColor;

    mBorderWidth = borderWidth;
    mBorderRadius = borderRadius;
}

@Override
protected void onBoundsChange(Rect bounds) {
    super.onBoundsChange(bounds);
    mPath.reset();

    // out rect
    mRect.set(bounds.left + mBorderWidth, bounds.top + mBorderWidth, bounds.right - mBorderWidth, bounds.bottom - mBorderWidth);
    mPath.addRoundRect(mRect, mBorderRadius, mBorderRadius, Path.Direction.CW);

    // inner rect
    mRect.set(bounds.left + 20, bounds.top + 20, bounds.right - 20, bounds.bottom - 20);
    mPath.addRoundRect(mRect, mBorderRadius, mBorderRadius, Path.Direction.CW);
}

@Override
public void draw(@NonNull Canvas canvas) {
    // kind of strock 
    mPaint.setShader(new LinearGradient(0, 0, 0, 100, startColor, endColor, Shader.TileMode.MIRROR));
    canvas.drawPath(mPath, mPaint);
}
@Override
public void setAlpha(int alpha) { mPaint.setAlpha(alpha);}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {mPaint.setColorFilter(colorFilter);}
@Override
public int getOpacity() {return PixelFormat.TRANSLUCENT;}
}

Основной:

Button but = ((Button)findViewById(R.id.but));
but.setBackground(new CustomDrawable(Color.parseColor("#FD659B"),
       Color.parseColor("#F76E63"),
       but.getPaddingLeft(), 100));

макет:

<Button
    android:id="@+id/but"
    android:layout_width="300dp"
    android:layout_height="80dp"
    android:background="@android:color/transparent"
    android:layout_centerInParent="true"
    android:text="Signin"/>
0 голосов
/ 16 мая 2018

Я не думаю, что мы можем установить градиент для обводки, но мы можем взломать то же самое, используя список слоев.

вы можете создать ниже нарисованный xml с желаемым градиентом

<item>
    <shape android:shape="rectangle">
        <!-- gradient for the stroke is set below -->
        <gradient
            android:angle="180"
            android:startColor="#555994"
            android:endColor="#b5b6d2"
            android:type="linear" />
        <corners android:radius="4dp"></corners>
    </shape>

</item>
<!-- stroke width has to be adjusted by setting left, right , top and bottom -->
<item android:left="4dp" android:right="4dp"
    android:top="4dp" android:bottom="4dp">
    <shape
        android:shape="rectangle">
        <solid android:color="@android:color/white"/>
    </shape>
</item>

Вы можете установить вышеприведенное рисование в макете / программно

button.setBackgroundResource (R.drawable.button_background);

...