package com.android.leanrengwuxian.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import com.android.leanrengwuxian.Util;
import java.text.DecimalFormat;
/**
* Created by 10090 on 2020/12/10.
*/
public class PieView extends View {
private static final String TAG = "PieView";
private float radius = Util.dpToPx(100);
RectF bouns = new RectF();
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int[] mAngleData = {60, 100, 80, 120};
private int[] mColorData = {Color.RED, Color.GRAY, Color.GREEN, Color.BLUE};
{
paint.setTextSize(Util.dpToPx(12));
paint.setTextAlign(Paint.Align.CENTER);
}
public PieView(Context context) {
super(context);
}
public PieView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public PieView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
bouns.set((int) (getWidth() / 2 - radius)
, (int) (getHeight() / 2 - radius)
, (int) (getWidth() / 2 + radius)
, (int) (getHeight() / 2 + radius));
}
DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int currentAngle = 0;
for (int i = 0; i < mAngleData.length; i++) {
paint.setColor(mColorData[i]);
canvas.drawArc(bouns, currentAngle, mAngleData[i], true, paint);
String value = df.format((float) mAngleData[i] * 100 / 360);
canvas.drawText(value + "%"
, (float) Math.cos(Math.toRadians(currentAngle + mAngleData[i] / 2)) * Util.dpToPx(120) + getWidth() / 2
, (float) Math.sin(Math.toRadians(currentAngle + mAngleData[i] / 2)) * Util.dpToPx(120) + getHeight() / 2
, paint);
currentAngle += mAngleData[i];
}
//绘制百分比文字
// paint.setColor(Color.BLACK);
// currentAngle = 0;
// for (int i = 0; i < mAngleData.length; i++) {
// canvas.drawText("50%"
// , (float) Math.cos(Math.toRadians(currentAngle + mAngleData[i] / 2)) * Util.dpToPx(50) + getWidth() / 2
// , (float) Math.sin(Math.toRadians(currentAngle + mAngleData[i] / 2)) * Util.dpToPx(50) + getHeight() / 2
// , paint);
// currentAngle += mAngleData[i];
// }
}
}
dp转px
/**
* Created by 10090 on 2020/11/20.
*/
public class Utils {
public static float dpToPx(float dp){
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, Resources.getSystem().getDisplayMetrics());
}
}