【问题标题】:Decorating a JFreeChart装饰 JFreeChart
【发布时间】:2010-11-16 17:08:46
【问题描述】:

我想在角落里用时间戳装饰我生成的所有 JFreeCharts。 JFreeChart 框架内有没有办法在图表生成后在图像上绘制?

编辑:请注意,这些图表是在后台线程中生成并通过 servlet 分发的,因此没有 GUI,我不能只在单独的组件上显示时间戳。

【问题讨论】:

    标签: java jfreechart graphics2d


    【解决方案1】:

    一种方法是继承 ChartPanel 并覆盖 paint(Graphics) 方法以首先链接到 super.paint(Graphics),然后在图表顶部呈现附加文本。

    这对我来说感觉有点 hacky,我个人更喜欢简单地将 ChartPanel 添加到另一个容器 JPanel 以及代表时间戳的 JLabel

    【讨论】:

    • 第一个“hacky”解决方案会起作用,我确实想过,但我希望 JFreeChart 能够更直接地支持这样的事情。如果没有更好的东西出现,我会接受。第二个对我不起作用,因为我没有在桌面应用程序中显示它;我只是在后台线程中生成图表并通过 servlet 分发它们。
    • 我现在意识到,再读一遍,你的两个答案都假设我正在运行一个桌面应用程序,所以这对我不起作用。不过,它可能适用于其他人,所以我仍然支持它。
    【解决方案2】:

    在此处查看此论坛帖子:

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

    【讨论】:

    • 我真的不想使用 ImageIcon,因为我想显示动态字符串而不是固定图像,但我想如果找不到的话,我可以为字符串生成图像更好。
    【解决方案3】:

    org.jfree.chart.JFreeChartaddSubtitle() 方法可能是一个合适的替代方案。

    【讨论】:

    • 这当然可以让我获得图像上的时间戳,我对此投了赞成票,但这是以图表渲染的一些空间为代价的。由于角落里经常有空白,我想将时间戳分层放在图像之上,而不是为其分配空间。
    • @Robert J. Walker:我同意你对空间的担忧。你可以看看PolarPlot,它有addCornerTextItem()。我通常只是编辑主标题以包含“截至 ”,其中 表示查询日期。
    【解决方案4】:

    经过一番折腾,我找到了一个解决方案,可以让您在 JFreeChart 完成后在图像上任意绘制,所以我将其发布在这里以供后人使用。就我而言,我正在将图表写入 OutputStream,因此我的代码如下所示:

    BufferedImage chartImage = chart.createBufferedImage(width, height, null);
    Graphics2D g = (Graphics2D) chartImage.getGraphics();
    /* arbitrary drawing happens here */
    EncoderUtil.writeBufferedImage(chartImage, ImageFormat.PNG, outputStream);
    

    【讨论】:

      【解决方案5】:

      根据我的经验,向 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 );
      

      【讨论】:

        猜你喜欢
        • 2011-09-03
        • 2015-11-18
        • 1970-01-01
        • 2020-01-11
        • 1970-01-01
        • 2013-05-07
        • 2014-01-14
        • 1970-01-01
        • 2015-02-01
        相关资源
        最近更新 更多