Android ShapeDrawable程序化设置背景和边框

7

我有一个ShapeDrawable

final ShapeDrawable drawable = new ShapeDrawable(shape);
drawable.getPaint().setStyle(Paint.Style.FILL);
drawable.getPaint().setColor(0xFFffffff);

我希望为这个可绘制对象设置边框颜色和宽度。我尝试使用 setStyle(Paint.Style.FILL_AND_STROKE),但它会将背景和边框设置为相同的颜色。

你找到了一种方法来做那件事吗? - Alvaro Rivoir
2个回答

4

如果你有一个视图,如TextView,需要设置背景和边框,你可以使用以下Kotlin代码实现:

val view = findViewById(R.id.miTextView) as TextView
val borderColor : Int = Color.GRAY,
val backgroundColor : Int = Color.GRAY,
val borderWidth : Float = 5F,
val borderRadius : Float = 15F
val borderShape = ShapeDrawable().apply {
    shape = RoundRectShape(floatArrayOf(borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius), null, null)
    paint.color = borderColor
    paint.style = Paint.Style.STROKE;
    paint.strokeWidth = borderWidth;
}
val backgroundShape = ShapeDrawable().apply {
    shape = RoundRectShape(floatArrayOf(borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius), null, null)
    paint.color = backgroundColor
    paint.style = Paint.Style.FILL_AND_STROKE;
}
val composite = LayerDrawable(arrayOf<Drawable>(backgroundShape, borderShape))
view.background = composite

3

使用

drawable.getPaint().setStyle(Paint.Style.STROKE);
drawable.getPaint().setStrokeWidth(2); // in pixel

那么缺失的边框颜色呢?这个回答不应该被点赞,因为它没有回答主要问题。 - d.aemon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接