使用代码设置边框圆角等

不必每次都要创建一个xml作为bg了。

    /**
     * 定义背景
     * @param cornerDp 边框四角弧度 默认5
     * @param borderPx 边框粗细值 默认1
     * @param borderCorlor 边框颜色值 默认 透明为0
     * @param bgColor 背景色值,默认 透明为0
     * @param context 上下文
     * @return GradientDrawable
     */
    public static GradientDrawable drawCornerBorderBg(int cornerDp, int borderPx, int borderCorlor, int bgColor, Context context){
        GradientDrawable mgDrawable= new GradientDrawable();
        mgDrawable.setShape(GradientDrawable.RECTANGLE);
        int cornerDpDef = 5;
        if (cornerDp >=0) {
            cornerDpDef = cornerDp;
        }
        int borderPxDef = 1;
        if (borderPx >=0) {
            borderPxDef = borderPx;
        }
        int borderColorDef = Color.TRANSPARENT;
        if (borderCorlor !=0) {
            borderColorDef = context.getResources().getColor(borderCorlor);
        }
        int bgColorDef = Color.TRANSPARENT;
        if (bgColor != 0) {
            bgColorDef = context.getResources().getColor(bgColor);
        }
        //设置边框颜色和宽度
        mgDrawable.setStroke(borderPxDef, borderColorDef);
        mgDrawable.setCornerRadius(dip2px(context, cornerDpDef));
        mgDrawable.setColor(bgColorDef);
        return mgDrawable;
        //
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,915评论 1 32
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 8,008评论 0 3
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 10,050评论 0 5
  • 一、简历准备 1、个人技能 (1)自定义控件、UI设计、常用动画特效 自定义控件 ①为什么要自定义控件? Andr...
    lucas777阅读 10,656评论 2 54
  • 这几天,江西一所小学内发生的家长刺伤孩子事件引起了社会的广泛关注: 5月10日,江西上饶第五小学 一名年仅十岁的男...
    静月月阅读 937评论 0 0

友情链接更多精彩内容