【Android】自定义View实现信封红蓝边/收货地址线条
- 先看效果图
- 实现步骤
1.自定义View:
public class MailLineView extends View {
//颜色块的宽度,可定义成XML属性,颜色值也可以定义为XML属性,请自行处理
private int colorWidth = 7;
//空白块的宽度
private int emptyWidth = 1;
public MailLineView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MailLineView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MailLineView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
//获取View宽度
int viewHeight = getHeight();
//绘制完成的长度
int drawLength = 0;
Paint paint = new Paint();
paint.setAntiAlias(true);
int count = 0;
//使用canvas循环绘制颜色块
while (drawLength < getWidth()) {
drawLength += emptyWidth * viewHeight;
count++;
//切换颜色
if (count % 2 == 1) {
paint.setColor(Color.rgb(255, 134, 134));
} else {
paint.setColor(Color.rgb(134, 194, 255));
}
//使用路径绘制一个菱形
Path path = new Path();
path.moveTo(drawLength, viewHeight);// 此点为多边形的起点
path.lineTo(drawLength + colorWidth * viewHeight - viewHeight, viewHeight);
path.lineTo(drawLength + colorWidth * viewHeight, 0);
path.lineTo(drawLength + viewHeight, 0);
path.close(); // 使这些点构成封闭的多边形
canvas.drawPath(path, paint);
drawLength += colorWidth * viewHeight;
}
}
}
2.在XML中添加MailLineView:
<com.smartown.library.ui.widget.MailLineView
android:layout_width="match_parent"
android:layout_height="4dp">
</com.smartown.library.ui.widget.MailLineView>
- 总结
实现过程比较简单,可以参考这种方式,使用自定义View实现更多的效果。
有需要可以在attrs.xml中定义View属性提升扩展性。