废话不多说先上效果图
蓝框部分为自定义View
红框部分为效果所在
直接上源码核心也就40多行,也比较简单
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
/**
* Created by yufeng on 2016/10/31.
*/
public class BottomHalfCircleRelativeLayout extends RelativeLayout {
private int width = 0;
private int count;
private int height;
private Paint paint;
private int color;
private int halfRadius;//px单位
private float leftSpace = halfRadius;
public BottomHalfCircleRelativeLayout(Context context) {
this(context, null);
}
public BottomHalfCircleRelativeLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BottomHalfCircleRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if (attrs != null) {
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.BottomHalfRelativeLayout);
color = ta.getColor(R.styleable.BottomHalfRelativeLayout_color, Color.WHITE);
halfRadius = SM.dip2px(getContext(), ta.getInteger(R.styleable.BottomHalfRelativeLayout_halfRadius, 3) * 2);
}
}
private void init() {
if (getWidth() == 0) measure(0, 0);
width = getMeasuredWidth();
height = getMeasuredHeight();
count = (width - halfRadius * 2) / halfRadius;//计算有多少个间隔和半圆 间隔是半圆-1
//计算除了左边和右边 画间隔和半圆之后还空余的地方
int space = (width - halfRadius * 2) % halfRadius;
//因为间隔是半圆的-1 所以如果是双数就要删去一个位置
if (count % 2 == 0) {
//将空余位置space和双数删除的位置分配给两边
leftSpace = halfRadius + space / 2f + halfRadius / 2f;
} else {
//将空余位置space分配给两边
leftSpace = halfRadius + space / 2f;
}
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(color);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (width == 0) init();
float x = leftSpace;
float y = height - halfRadius / 2;
for (int i = 0; i < count / 2; i++) {
//画园
RectF oval2 = new RectF(x, y, x + halfRadius, height + halfRadius / 2);// 设置个新的长方形,扫描测量
canvas.drawArc(oval2, 180, 180, true, paint);
//加上间隔
x += halfRadius * 2;
}
}
}
attrs.xml中添加
<declare-styleable name="BottomHalfRelativeLayout">
<attr name="color" format="color" />
<attr name="halfRadius" format="integer" />
</declare-styleable>