Android ShapeDrawable

今天做项目碰到一个这样的情况,就是颜色指示框,用的是正方形边框是黑色的,里面填充颜色,颜色值是动态的,为了解决这个问题,查了好多资料,终于找到解决的方法,利用ShapeDrawable,我们自定义一个CustomShapeDrawable类继承ShapeDrawable,代码:

public class CustomShapeDrawable extends ShapeDrawable {
    privatefinal Paint fillpaint, strokepaint;
 
    publicCustomShapeDrawable(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
    protectedvoid onDraw(Shape shape, Canvas canvas, Paint paint) {
       shape.draw(canvas, fillpaint);
       shape.draw(canvas, strokepaint);
    }
}

 效果图如下:

Android <wbr>ShapeDrawable

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ShapeDrawableAndroid中的一个Drawable类型,它可以让开发者自定义绘制出各种形状的图形。下面是ShapeDrawable的用法: 1.创建一个ShapeDrawable对象 可以通过如下方式创建一个ShapeDrawable对象: ``` ShapeDrawable shapeDrawable = new ShapeDrawable(); ``` 2.设置ShapeDrawable的形状 在创建ShapeDrawable对象后,需要设置它的形状。ShapeDrawable支持以下几种形状: 矩形(RectangleShape): ``` shapeDrawable.setShape(new RectShape()); ``` 圆形(OvalShape): ``` shapeDrawable.setShape(new OvalShape()); ``` 线条(LineShape): ``` shapeDrawable.setShape(new LineShape()); ``` 圆角矩形(RoundRectShape): ``` float[] radii = {10, 10, 10, 10, 0, 0, 0, 0}; // 每个角的半径 RectF rectF = new RectF(0, 0, 100, 100); // 矩形的位置和大小 shapeDrawable.setShape(new RoundRectShape(radii, rectF, radii)); ``` 3.设置ShapeDrawable的颜色 设置ShapeDrawable的颜色可以使用setColor()方法: ``` shapeDrawable.getPaint().setColor(Color.RED); ``` 4.设置ShapeDrawable的边框 设置ShapeDrawable的边框可以使用setStroke()方法: ``` shapeDrawable.getPaint().setStrokeWidth(5); shapeDrawable.getPaint().setStyle(Paint.Style.STROKE); shapeDrawable.getPaint().setColor(Color.BLACK); ``` 5.使用ShapeDrawable 最后,可以将ShapeDrawable对象设置为View的背景或者ImageView的src属性,或者直接在自定义绘制的时候使用它。例如,在Activity的onCreate()方法中设置一个矩形ShapeDrawable的背景: ``` ShapeDrawable shapeDrawable = new ShapeDrawable(); shapeDrawable.setShape(new RectShape()); shapeDrawable.getPaint().setColor(Color.RED); View view = findViewById(R.id.view); view.setBackground(shapeDrawable); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值