Android如何创建一个三等分覆盖不同颜色背景的圆
2017-03-28 本文已影响272人
af274772f108
一次参加面试的时候面试官问到了这样的一个问题,如何自定义一个view然后实现三等分圆并覆盖不同颜色背景,当时就尴尬了。如果直接画一个圆覆盖同一种颜色肯定是没问题,三等分实在是没接触过,后来才知道原来Canvas直接提供了画扇形的方法,直接画三个120度的扇形覆盖不同颜色这样就拼成了一个圆,源码如下,不细说了:
圆.png
public class MyView2 extends View {
private static final float RADIUS = 120f;
private static final int[] COLORS = new int[]{0xFFF06292, 0xFF81C784, 0xFFE57373};
private Paint mPaint;
private Context mContext;
public MyView2(Context context) {
super(context);
mContext = context;
}
public MyView2(Context context, AttributeSet attr) {
super(context, attr);
mContext = context;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
initPaint();
drawUI(canvas);
}
private void initPaint() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.FILL);
}
private void drawUI(Canvas canvas) {
WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
int h = windowManager.getDefaultDisplay().getHeight();
int w = windowManager.getDefaultDisplay().getWidth();
float start = 0f;
for (int i = 0; i < COLORS.length; i++) {
mPaint.setColor(COLORS[i]);
RectF rectF = new RectF(w / 2 - 200, h / 2 - 200, w / 2 + 200, h / 2 + 200);
canvas.drawArc(rectF, start, RADIUS, true, mPaint);
start += RADIUS;
}
}
}