【发布时间】:2010-11-16 17:08:46
【问题描述】:
我想在角落里用时间戳装饰我生成的所有 JFreeCharts。 JFreeChart 框架内有没有办法在图表生成后在图像上绘制?
编辑:请注意,这些图表是在后台线程中生成并通过 servlet 分发的,因此没有 GUI,我不能只在单独的组件上显示时间戳。
【问题讨论】:
标签: java jfreechart graphics2d
我想在角落里用时间戳装饰我生成的所有 JFreeCharts。 JFreeChart 框架内有没有办法在图表生成后在图像上绘制?
编辑:请注意,这些图表是在后台线程中生成并通过 servlet 分发的,因此没有 GUI,我不能只在单独的组件上显示时间戳。
【问题讨论】:
标签: java jfreechart graphics2d
一种方法是继承 ChartPanel 并覆盖 paint(Graphics) 方法以首先链接到 super.paint(Graphics),然后在图表顶部呈现附加文本。
这对我来说感觉有点 hacky,我个人更喜欢简单地将 ChartPanel 添加到另一个容器 JPanel 以及代表时间戳的 JLabel。
【讨论】:
在此处查看此论坛帖子:
http://www.jfree.org/phpBB2/viewtopic.php?f=3&t=27939
使用 ImageIcon 作为水印:
ImageIcon icon = new ImageIcon(new URL(watermarkUrl));
Image image = icon.getImage();
chart.setBackgroundImage(image);
chart.setBackgroundImageAlignment(Align.CENTER);
chart.getPlot().setBackgroundAlpha(0.2f);
【讨论】:
org.jfree.chart.JFreeChart 的 addSubtitle() 方法可能是一个合适的替代方案。
【讨论】:
PolarPlot,它有addCornerTextItem()。我通常只是编辑主标题以包含“截至 ”,其中 表示查询日期。
经过一番折腾,我找到了一个解决方案,可以让您在 JFreeChart 完成后在图像上任意绘制,所以我将其发布在这里以供后人使用。就我而言,我正在将图表写入 OutputStream,因此我的代码如下所示:
BufferedImage chartImage = chart.createBufferedImage(width, height, null);
Graphics2D g = (Graphics2D) chartImage.getGraphics();
/* arbitrary drawing happens here */
EncoderUtil.writeBufferedImage(chartImage, ImageFormat.PNG, outputStream);
【讨论】:
根据我的经验,向 JFreeChart 添加自定义信息的最佳方式是: - 实例化一个同类型图表的BufferedImage; - 在 BufferedImage 上绘制; - 使用 XYImageAnnotation 将图像添加到当前 Plot。
这是代码的指南:
// retrieve image type and create another BufferedImage
int imgType = chart.createBufferedImage(1,1).getType();
BufferedImage bimg = new BufferedImage(width, height, bimg.getType);
// here you can draw inside the image ( relative x & y )
Graphics2D g2 = (Graphics2D) bimg.getGraphics();
g2.drawString("Hello, JFreeChart " + timestamp, posX, posY );
// instantiate the image annotation, then add to the plot
XYImageAnnotation a = new XYImageAnnotation( x, y, bimg, RectangleAnchor.LEFT );
chart.getPlot().addAnnotation( a );
【讨论】: