Android Studio 自定义View绘制简单饼状图

代码展示

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);
    }
}

效果

在这里插入图片描述

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值