今天做项目碰到一个这样的情况,就是颜色指示框,用的是正方形边框是黑色的,里面填充颜色,颜色值是动态的,为了解决这个问题,查了好多资料,终于找到解决的方法,利用ShapeDrawable,我们自定义一个CustomShapeDrawable类继承ShapeDrawable,代码:
public class CustomShapeDrawable extends ShapeDrawable {
private final Paint fillpaint, strokepaint; public CustomShapeDrawable(Shape s, int fill, int stroke, int strokeWidth) {
super(s);
fillpaint = new Paint(this.getPaint());
fillpaint.setColor(fill);
strokepaint = new Paint(fillpaint);
strokepaint.setStyle(Paint.Style.STROKE);
strokepaint.setStrokeWidth(strokeWidth);
strokepaint.setColor(stroke);
} @Override
protected void onDraw(Shape shape, Canvas canvas, Paint paint) {
shape.draw(canvas, fillpaint);
shape.draw(canvas, strokepaint);
}
}
效果图如下: