代码展示
package com.example.day6;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class Pie extends View {
int x;
int y;
Paint paint;
Canvas mCancas;
public Pie(Context context, AttributeSet attrs) {
super(context, attrs);
x = getResources().getDisplayMetrics().widthPixels / 2;
y = getResources().getDisplayMetrics().heightPixels / 2;
initPaint();
}
private void initPaint() {
paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
paint.setDither(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mCancas = canvas;
drawPieChart();
}
public void drawPieChart() {
int left = x - 400;
int right = x + 400;
int top = y + 100 - 400;
int bottom = y + 100 + 400;
float startAngle = 2f;
paint.setColor(Color.BLUE);
mCancas.drawArc(left, top, right, bottom, startAngle, 30f, true, paint);
startAngle += 30f;
paint.setColor(Color.YELLOW);
mCancas.drawArc(left, top, right, bottom, startAngle, 41f, true, paint);
startAngle += 41f;
paint.setColor(Color.RED);
mCancas.drawArc(left, top, right, bottom, startAngle, 59f, true, paint);
startAngle += 59f;
paint.setColor(Color.GREEN);
mCancas.drawArc(left, top, right, bottom, startAngle, 80f, true, paint);
startAngle += 80f;
paint.setColor(Color.YELLOW);
mCancas.drawArc(left, top, right, bottom, startAngle, 140f, true, paint);
startAngle += 140f;
paint.setColor(Color.BLACK);
mCancas.drawArc(left, top, right, bottom, startAngle, 10f, true, paint);
}
}
效果