当一条边的两个圆角半径和超过该边长度时,需要特殊处理下,可以按照如下步骤实现:
依次对每条边进行如下操作:
记该边的两个圆角半径和为s,该边长为l,若s大于l则四个圆角进行如下操作
ltCorner=ltCorner*(l/s), rtCorner=rtCorner*(l/s), lbCorner=lbCorner*(l/s), rbCorner=rbCorner*(l/s)
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by wanjian on 2017/9/15.
*/
public class RadiusView extends View {
private float lt, rt, rb, lb;
private Path path = new Path();
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public RadiusView(Context context) {
super(context);
init();
}
public RadiusView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
}
public void setRadius(float lt, float rt, float rb, float lb) {
this.lt = lt;
this.rt = rt;
this.rb = rb;
this.lb = lb;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int w = getWidth();
int h = getHeight();
if (lt + rt > w) {
float scale = w / (lt + rt);
lt *= scale;
rt *= scale;
rb *= scale;
lb *= scale;
}
if (rt + rb > h) {
float scale = h / (rt + rb);
lt *= scale;
rt *= scale;
rb *= scale;
lb *= scale;
}
if (rb + lb > h) {
float scale = w / (rb + lb);
lt *= scale;
rt *= scale;
rb *= scale;
lb *= scale;
}
if (lt + lb > h) {
float scale = w / (lt + lb);
lt *= scale;
rt *= scale;
rb *= scale;
lb *= scale;
}
path.reset();
path.arcTo(0, 0, lt * 2, lt * 2, 180, 90, false);
path.arcTo(w - rt * 2, 0, w, rt * 2, -90, 90, false);
path.arcTo(w - rb * 2, h - rb * 2, w, h, 0, 90, false);
path.arcTo(0, h - lb * 2, lb * 2, h, 90, 90, false);
path.close();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL);
canvas.drawPath(path, paint);
}
}