feiyu02
2024-05-31 da431c25dfe5122e4ed70372da36ede3e4eaec4a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.flightfeather.uav.common.chart
 
import org.jfree.chart.ChartFactory
import org.jfree.chart.ChartUtils
import org.jfree.chart.JFreeChart
import org.jfree.chart.title.TextTitle
import org.jfree.data.category.DefaultCategoryDataset
import java.awt.Font
import java.io.ByteArrayOutputStream
 
/**
 * 图表生成
 * @date 2024/5/31
 * @author feiyu02
 */
object ChartUtil {
 
    data class ChartValue(val x: String?, val y: Number)
 
    fun line(title: String, dataset: DefaultCategoryDataset): JFreeChart {
        val line = ChartFactory.createLineChart(title, "时间", "浓度", dataset)
        line.categoryPlot.domainAxis.labelFont = Font("宋体", Font.PLAIN, 12)
        line.categoryPlot.rangeAxis.labelFont = Font("宋体", Font.PLAIN, 12)
        return line
    }
 
    fun lineToByteArray(title: String, dataset: DefaultCategoryDataset):ByteArray {
        val chart = line(title, dataset)
        val output = ByteArrayOutputStream()
        ChartUtils.writeChartAsPNG(output, chart, 600, 400)
        val byteArray = output.toByteArray()
        output.flush()
        output.close()
        return byteArray
    }
 
    fun newDataset(dataList:List<ChartValue>, seriesName:String): DefaultCategoryDataset {
        val dataset = DefaultCategoryDataset()
        dataList.forEach {
            dataset.setValue(it.y, seriesName, it.x)
        }
        return dataset
    }
}