尝试绘制一个按钮:如何设置描边颜色以及如何在不知道高度的情况下将渐变“对齐”到底部?

2024-01-02

我正在以编程方式创建一个按钮。它是圆形的,具有渐变背景,工作正常且看起来不错,但我无法做我想做的两件事:

  1. 使用给定颜色设置 1 像素描边。我尝试了 getPaint().setStroke(),但无法弄清楚如何设置描边颜色。我该怎么做呢?
  2. 将渐变与按钮底部对齐,无论按钮的高度是多少。这可能吗?

作为参考,这是我正在使用的代码:

Button btn = new Button(context);
btn.setPadding(7, 3, 7, 5);
btn.setTextColor(text_color);

// Create a gradient for the button. Height is hardcoded to 30 (I don't know the height beforehand). 
// I wish I could set the gradient aligned to the bottom of the button.
final Shader shader = new LinearGradient(0, 0, 0, 30,
    new int[] { color_1, color_2 },
    null, Shader.TileMode.MIRROR);

float[] roundedCorner = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 }
ShapeDrawable normal = new ShapeDrawable(new RoundRectShape(roundedCorner, null, null));
normal.getPaint().setShader(shader);
normal.setPadding(7, 3, 7, 5);

// Create a state list (I suppressed settings for pressed).
StateListDrawable state_list = new StateListDrawable();
state_list.addState(new int[] { }, normal);

btn.setBackgroundDrawable(state_list);

关于你的第一个问题,我也遇到了这个问题,而且 Drawables 本身似乎没有任何合适的方法(我正在使用ShapeDrawable) 或 Paint 类。然而,我能够延长ShapeDrawable并重写绘制方法,如下所示,得到相同的结果:

public class CustomBorderDrawable extends ShapeDrawable {
    private Paint fillpaint, strokepaint;
    private static final int WIDTH = 3; 

    public CustomBorderDrawable(Shape s) {
        super(s);
        fillpaint = this.getPaint();
        strokepaint = new Paint(fillpaint);
        strokepaint.setStyle(Paint.Style.STROKE);
        strokepaint.setStrokeWidth(WIDTH);
        strokepaint.setARGB(255, 0, 0, 0);
    }

    @Override
    protected void onDraw(Shape shape, Canvas canvas, Paint fillpaint) {
        shape.draw(canvas, fillpaint);
        shape.draw(canvas, strokepaint);
    }

    public void setFillColour(int c){
        fillpaint.setColor(c);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尝试绘制一个按钮:如何设置描边颜色以及如何在不知道高度的情况下将渐变“对齐”到底部? 的相关文章

随机推荐