大多数文章里面都是些如何使用xml进行设置圆角效果,但是在写第三方库的时候往往最后打包成一个jar文件,无法把xml打进去,这个时候我们不妨把这部分的xml代码放到Java中写,同样简单。
实现的思路也比较容易理解,因为在XML中无法也是先画一个图形,然后设置这个控件的backgroundDrawable,Java中我们也同样来这么做:
int borderWidth = 0;// 加边框后会出现空心圆角矩形的效果,所以设置为0
float[] outerRadius = new float[8];
float[] innerRadius = new float[8];
for (int i = 0; i < 8; i++) {
outerRadius[i] = radius + borderWidth;
innerRadius[i] = radius;
}
ShapeDrawable shapeDrawable = // 创建图形drawable
new ShapeDrawable(// 创建圆角矩形
new RoundRectShape(outerRadius,
new RectF(borderWidth, borderWidth, borderWidth, borderWidth),
innerRadius));
shapeDrawable.getPaint().setColor(color);// 使用指定的颜色绘制,即背景颜色
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// 高版本SDK使用新的API
view.setBackground(shapeDrawable);
} else {
view.setBackgroundDrawable(shapeDrawable);
}
不懂的地方可以评论,或者加入LemonKit技术交流QQ群:370157608
LemonKit移动端全平台极速开发框架开源地址如下:
版本名称 | Github地址 |
---|---|
Android版本 | https://github.com/1em0nsOft/LemonKit4Android |
iOS ObjC版本 | https://github.com/1em0nsOft/LemonKit4iOS |
iOS Swift版本 | https://github.com/1em0nsOft/LemonKit4iOS-Swift |