package com.example.hellojnicallback;
import android.content.Context;
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 androidx.annotation.Nullable;
public class PieChart extends View {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private static final float RADIUS = Util.dp2px(150);
private static final float LENGTH = Util.dp2px(25);
private static final float PULLED_OUT_INDEX = 0;
RectF bounds = new RectF();
private static final int[] angles = {60, 100, 120, 80};
private static final int[] colors = {Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW};
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
paint.setColor(Color.RED);
bounds.set(getWidth()/2-RADIUS, getHeight()/2-RADIUS, getWidth()/2+RADIUS, getHeight()/2+RADIUS);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int currentAngel = 0;
for (int i = 0; i < angles.length; i++) {
paint.setColor(colors[i]);
canvas.save(); // 记录绘制前的位置信息
if (i == PULLED_OUT_INDEX) {
float dx = (float) (LENGTH * Math.cos(Math.toRadians(currentAngel+angles[i]/2.0f)));
float dy = (float) (LENGTH * Math.sin(Math.toRadians(currentAngel+angles[i]/2.0f)));
canvas.translate(dx, dy);
}
canvas.drawArc(bounds, currentAngel, angles[i], true, paint);
canvas.restore(); // 恢复绘制前的信息
currentAngel += angles[i];
}
}
public PieChart(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
}
评论