不必每次都要创建一个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);
}
网友评论