Android之自定义控件实现天气温度折线图和饼状图

以前写了个天气的APP,最近把他更新了一个版本,就抽取其中的天气温度折现图这个功能写了这篇博客,来与大家分享,希望对你有所帮助。

效果如图:

代码:

MainActivity.Java

/****
 * 饼状图和天气折线图
 */
public class MainActivity extends AppCompatActivity {

    private WeatnerChartView chart1;
    private WeatnerChartView chart2;
    private PinChart pinChart;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView()
    {
        chart1= (WeatnerChartView) findViewById(R.id.weather_char1);
        chart2= (WeatnerChartView) findViewById(R.id.weather_char2);
        pinChart= (PinChart) findViewById(R.id.pinchart);
        initData();
    }
    private void initData()
    {
        ArrayList<WeatherItem> list= new ArrayList<WeatherItem>();
        list.add(new WeatherItem("",18));
        list.add(new WeatherItem("",40));
        list.add(new WeatherItem("", -1));
        list.add(new WeatherItem("",1));
        list.add(new WeatherItem("",6));
        list.add(new WeatherItem("",2));
        list.add(new WeatherItem("", 33));
        chart1.SetTuView(list, "最高温度:");//单位: 摄氏度
        chart1.invalidate();
        ArrayList<WeatherItem> list1= new ArrayList<WeatherItem>();
        list1.add(new WeatherItem("",1));
        list1.add(new WeatherItem("",15));
        list1.add(new WeatherItem("", -6));
        list1.add(new WeatherItem("",-2));
        list1.add(new WeatherItem("", 3));
        list1.add(new WeatherItem("",-1));
        list1.add(new WeatherItem("",11));
        chart2.SetTuView(list1, "最低温度:");
        chart2.invalidate();
    }

}

饼状图自定义控件 PinChart.java

@SuppressLint("DrawAllocation") public class PinChart extends View {

    static Canvas c;
    private Paint[] mPaints;
    private Paint mTextPaint;
    private RectF mBigOval;
    public float[] mSweep = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    private static final float SWEEP_INC = 1;

    public static float[] humidity = { 110, 40, 50, 60, 50, 50 };

    public PinChart(Context context) {
        super(context);

    }

    public PinChart(Context context, AttributeSet atr) {
        super(context, atr);
    }

    @SuppressLint("DrawAllocation") @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(Color.TRANSPARENT);// 设置背景颜色(透明)

        mPaints = new Paint[humidity.length];
        for (int i = 0; i < humidity.length; i++) {
            mPaints[i] = new Paint();
            mPaints[i].setAntiAlias(true);
            mPaints[i].setStyle(Paint.Style.FILL);
            mPaints[i].setColor(0x880FF000 + i * 0x019e8860);
        }

        mBigOval = new RectF(40, 30, 220, 200);// 饼图的四周边界-->左,上,右,下

        mTextPaint = new Paint();// 绘制文本
        mTextPaint.setAntiAlias(true);
        mTextPaint.setColor(Color.WHITE);
        mTextPaint.setTextSize(16F);// 设置温度值的字体大小
        float start = 0;
        for (int i = 0; i < humidity.length; i++) {
            canvas.drawArc(mBigOval, start, mSweep[i], true, mPaints[i]);
            start += humidity[i];
            if (mSweep[i] < humidity[i]) {
                mSweep[i] += SWEEP_INC;
            }
            canvas.drawRect(new RectF(300, 30 + 15 * i, 312, 42 + 15 * i),
                    mPaints[i]);
            canvas.drawText("测试模块" + i, 320, 40 + 15 * i, mTextPaint);
        }
        invalidate();
    }

}

自定义控件 WeatnerChartView.java

public class WeatnerChartView extends View {
    private ArrayList<WeatherItem> items;
    private String unit;
    private String yFormat = "0";

    private Context context;

    public void SetTuView(ArrayList<WeatherItem> list, String unitInfo) {
        this.items = list;
        this.unit = unitInfo;
    }

    public WeatnerChartView(Context ct) {
        super(ct);
        this.context = ct;
    }

    public WeatnerChartView(Context ct, AttributeSet attrs) {
        super(ct, attrs);
        this.context = ct;
    }

    public WeatnerChartView(Context ct, AttributeSet attrs, int defStyle) {
        super(ct, attrs, defStyle);
        this.context = ct;
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (items == null) {
            return;
        }

        int height = getHeight();
        int width = getWidth();

        int split = dip2px(context, 8);
        int marginl = width / 24;//12
        int margint = dip2px(context, 60);
        int margint2 = dip2px(context, 25);
        int bheight = height - margint - 2 * split;

        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.parseColor("#ffffff"));//#7fffffff

        paint.setStrokeWidth(4);
        paint.setStyle(Style.STROKE);
        // 画单位
        Paint p = new Paint();
        p.setAlpha(0x0000ff);
        p.setTextSize(sp2px(context, 15));
        p.setColor(Color.parseColor("#28bbff"));
        canvas.drawText(unit, split, margint2 + split * 2, p);

        // 画X坐标
        ArrayList<Integer> xlist = new ArrayList<Integer>();
        paint.setColor(Color.GRAY);
        for (int i = 0; i < items.size(); i++) {
            int span = (width - 2 * marginl) / items.size();
            int x = marginl + span / 2 + span * i;
            xlist.add(x);
            drawText(items.get(i).getX(), x, split * 2, canvas);
        }

        float max = Float.MIN_VALUE;
        float min = Float.MAX_VALUE;
        for (int i = 0; i < items.size(); i++) {
            float y = items.get(i).getY();
            if (y > max) {
                max = y;
            }
            if (y < min) {
                min = y;
            }
        }

        float span = max - min;
        if (span == 0) {
            span = 6.0f;
        }
        max = max + span / 6.0f;
        min = min - span / 6.0f;

        // 获取点集合
        Point[] mPoints = getPoints(xlist, max, min, bheight, margint);

        // 画线
        paint.setColor(Color.parseColor("#7fffffff"));
        paint.setStyle(Style.STROKE);
        paint.setStrokeWidth(3);//8
        drawLine(mPoints, canvas, paint);

        // 画点
        paint.setColor(Color.parseColor("#28bbff"));
        paint.setStyle(Style.FILL);
        for (int i = 0; i < mPoints.length; i++) {
            canvas.drawCircle(mPoints[i].x, mPoints[i].y, 8, paint);//radius=12
            String yText = new java.text.DecimalFormat(yFormat).format(items
                    .get(i).getY());
            drawText(yText+"°", mPoints[i].x,
                    mPoints[i].y - dip2px(context, 12), canvas);
        }
    }

    private Point[] getPoints(ArrayList<Integer> xlist, float max, float min,
            int h, int top) {
        Point[] points = new Point[items.size()];
        for (int i = 0; i < items.size(); i++) {
            int ph = top + h
                    - (int) (h * ((items.get(i).getY() - min) / (max - min)));
            points[i] = new Point(xlist.get(i), ph);
        }
        return points;
    }

    private void drawLine(Point[] ps, Canvas canvas, Paint paint) {
        Point startp = new Point();
        Point endp = new Point();
        for (int i = 0; i < ps.length - 1; i++) {
            startp = ps[i];
            endp = ps[i + 1];
            canvas.drawLine(startp.x, startp.y, endp.x, endp.y, paint);
        }
    }

    private void drawText(String text, int x, int y, Canvas canvas) {
        Paint p = new Paint();
        p.setAlpha(0x0000ff);
        p.setTextSize(sp2px(context, 15));
        p.setTextAlign(Paint.Align.CENTER);
        p.setColor(Color.WHITE);
        canvas.drawText(text, x, y, p);
    }

    public ArrayList<WeatherItem> getItems() {
        return items;
    }

    public void setItems(ArrayList<WeatherItem> items) {
        this.items = items;
    }

    public String getyFormat() {
        return yFormat;
    }

    public void setyFormat(String yFormat) {
        this.yFormat = yFormat;
    }

    public int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
时间: 2024-11-04 01:44:56

Android之自定义控件实现天气温度折线图和饼状图的相关文章

Excel数据可视化应用(直方图、折线图、饼状图)

直方图:对比关系 直方图是一种统计报告图,是表示资料变化情况的主要工具.直方图由一系列高度不等的的纵向条纹或线段表示数据分布的情况.一般用横轴表示数据类型,纵轴表示分布情况. 例1: 1.右键单击图表的纵坐标轴数据,选择“设置坐标轴格式”命令打开窗格,在“坐标轴选项”下,各类数据设置如下: 2.右键单击图例,选择设置图例格式,选择靠上(或点击图表空白处,点击上方图表工具中的设计,选择下方左侧的“添加图表元素”,选择“图例”.“顶部”) 3.右键单击任一直条(单击一下会自动选择全部直条),选择“添

Android开源图表之树状图和饼状图的官方示例的整理

最近由于工作需要,所以就在github上搜了下关于chart的三方框架 官方地址https://github.com/PhilJay/MPAndroidChart 由于工作需要我这里整理了一份Eclipse版本的类库.(有需要要的留下邮箱) 这就是Code中的效果(树状图) 1 public class BarChartActivity extends Activity implements OnChartValueSelectedListener{ 2 3 private BarChart m

ECharts 报表事件联动系列四:柱状图,折线图,饼状图实现联动

代码如下: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>ECharts</title> <!-- <script src="http://echarts.baidu.com/dist/echarts.min.j

C# 绘制图表(柱状图,线性图,饼状图)

http://blog.csdn.net/gisfarmer/article/details/3736452 Chart饼状图,每根柱子的宽度: int a = Chart1.Series["Series1"].Points.Count;  Chart1.Series["Series1"].CustomProperties = "PointWidth=0.5";  Chart1.Width = Unit.Pixel(25 * a); 如果有多个S

【 D3.js 进阶系列 — 6.2 】 饼状图的拖拽

本文讲解稍微复杂一些的拖拽应用,即拖拽饼图的各部分. 在[入门 - 第 9.1 章]讲解了如何制作饼状图.饼状图的各部分是用具有宽度的弧线来表示的.在与用户进行交互的时候,如果每一部分都能拖拽,是很有趣的. 1.饼状图的绘制 与[入门 - 第 9.1 章]稍有有些不同,我们对饼状图的每一个区域都使用一个 g 标签将其包围起来,以便平移操作. var gAll = svg.append("g") .attr("transform","translate(&q

Android例子源码动态绘制折线、圆柱、饼状图

Android例子源码动态绘制折线.圆柱.饼状图 仿天气类app绘制饼状图.折线图.柱状图的实现效果,效果挺不错,例子没有使用第三方类库,全部都是使用Canvas实现.需要的朋友可以自己下载研究下. 下载地址:http://www.devstore.cn/code/info/999.html 运行截图:   

Android图表库MPAndroidChart(八)——饼状图的扩展:折线饼状图

Android图表库MPAndroidChart(八)--饼状图的扩展:折线饼状图 我们接着上文,饼状图的扩展,增加折现的说明,来看下我们要实现的效果 因为之前对MPAndroidChart的熟悉,所有我们就可以直接来实现了 一.基本实现 首先,就是我们的来看下他的定义布局 <com.github.mikephil.charting.charts.PieChart android:id="@+id/mPieChart" android:layout_width="mat

Android开发自定义控件实现一个饼状图

实现一个如图所示的控件,包括两部分,左边的饼状图和中间的两个小方块,及右边的两行文字 实现起来比较简单,只是一些绘图API的调用 核心代码在onDraw函数里边,,对静态控件进行绘制即可 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); /*饼状图的x坐标*/ float centreX= getWidth()/5; /*饼状图的y坐标*/ float centreY= getHeight()/2; /*

iOS:使用贝塞尔曲线绘制图表(折线图、柱状图、饼状图)

1.介绍: UIBezierPath :画贝塞尔曲线的path类 UIBezierPath定义 : 贝赛尔曲线的每一个顶点都有两个控制点,用于控制在该顶点两侧的曲线的弧度. 曲线的定义有四个点:起始点.终止点(也称锚点)以及两个相互分离的中间点. 滑动两个中间点,贝塞尔曲线的形状会发生变化. UIBezierPath :对象是CGPathRef数据类型的封装,可以方便的让我们画出 矩形 . 椭圆 或者 直线和曲线的组合形状 初始化方法: + (instancetype)bezierPath; /