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.labels.StandardCategoryItemLabelGenerator
|
import org.jfree.chart.labels.StandardCategorySeriesLabelGenerator
|
import org.jfree.chart.plot.CategoryPlot
|
import org.jfree.chart.renderer.category.LineAndShapeRenderer
|
import org.jfree.chart.title.TextTitle
|
import org.jfree.data.category.DefaultCategoryDataset
|
import java.awt.BasicStroke
|
import java.awt.Color
|
import java.awt.Font
|
import java.awt.Paint
|
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)
|
setLine(line)
|
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
|
}
|
|
/**
|
* 设置折线图样式
|
*/
|
private fun setLine(chart: JFreeChart) {
|
chart.legend.itemFont = Font("SimHei", Font.PLAIN, 16)
|
chart.title.font = Font("SimHei", Font.BOLD, 20)
|
chart.categoryPlot.apply {
|
backgroundPaint = Color(255, 255, 255)
|
rangeGridlinePaint = Color(200, 200, 200)
|
rangeGridlineStroke = BasicStroke(1f)
|
isRangeGridlinesVisible = true
|
}
|
}
|
|
private fun setRenderer(plot:CategoryPlot, datasetList:List<DefaultCategoryDataset>) {
|
val renderer = newBasicRenderer(paint = Color(191, 0, 0))
|
}
|
|
private fun newBasicRenderer(series:Int = 0, paint:Paint): LineAndShapeRenderer {
|
return LineAndShapeRenderer().apply {
|
legendItemLabelGenerator = StandardCategorySeriesLabelGenerator()
|
setSeriesStroke(series, BasicStroke(3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 2000f))
|
setSeriesShapesVisible(series, false)
|
setSeriesPaint(series, paint)
|
}
|
}
|
}
|