本文要实现的View如图:
考虑到其还要放入其他控件,直接继承RelativeLayout即可。
同时本文为了简单起见把自定义属性去掉了,直接写死各种属性。
要实现这种效果,主要是计算需要画多少个圆,通过观察我们可以轻易算出:
(长度-间隔)/(2*半径 + 间隔)
由于长度不一定刚好整除,所以我们需要考虑,首先获取剩余的长度:
(长度-间隔)%(2*半径 + 间隔)
接下来需要考虑这个多余的长度,将其平分加到间隔中去
看下源码吧,道理弄清了很简单:
public class SecondView extends RelativeLayout {
private int gap = 8;
private int radius = 10;
private Paint mPaint;
private float remain;
private float remainY;
private int circleNum;
private int circleNumY;
public SecondView(Context context) {
super(context);
init();
}
public SecondView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public SecondView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setDither(true);
mPaint.setColor(Color.WHITE);
mPaint.setStyle(Paint.Style.FILL);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
circleNum = (w - gap) / (2 * radius + gap);
circleNumY = (h - gap) / (2 * radius + gap);
remain = (w - gap) % (2 * radius + gap);
remainY = (h - gap) % (2 * radius + gap);
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
for (int i = 0; i < circleNum; ++i) {
canvas.drawCircle(gap + radius + remain / 2 + (gap + 2 * radius) * i, 0, radius, mPaint);
canvas.drawCircle(gap + radius + remain / 2 + (gap + 2 * radius) * i, getMeasuredHeight(), radius, mPaint);
}
for (int i = 0; i < circleNumY; ++i) {
canvas.drawCircle(0, gap + radius + remainY / 2 + (gap + 2 * radius) * i, radius, mPaint);
canvas.drawCircle(getMeasuredWidth(), gap + radius + remainY / 2 + (gap + 2 * radius) * i, radius, mPaint);
}
}
}