【问题标题】:Java: Paint a histogram via fillRect()Java:通过 fillRect() 绘制直方图
【发布时间】:2014-03-12 19:16:27
【问题描述】:

我喜欢制作直方图。使用drawLine(),这对我来说不是问题,但是当我尝试使用fillRect() 时,矩形是从上到下的。我想用drawLine() 绘制看起来与我的直方图相似的直方图。

这是我的代码:

public void paint(Graphics g) {

    super.paint(g); 
    int height = getHeight();
    int width = getWidth();
    int x =10;
    haufigkeit=model.getMap();
    for(int i = 1; i <= 45; i++) {
        int y;
        y = haufigkeit.get(i);            
        Color color = new Color(0, 0, (int)(150 + Math.random() * 100));
        g.setColor(color);

        // g.fillRect(x, 50, 10, y);

        // g.drawLine(x, height - 50, x, height- y);

        x+=20;
    }

}

需要改变什么?

【问题讨论】:

  • x, height-50, x, height-y 是无序的。将其更改为x, height - y, rectWidth, y,其中rectWidth 为每个矩形的宽度。
  • drawLine(x,height-50,x,height-y);我喜欢这样做。问题在于 fillRect(x,50,10,y);现在它是从上到下绘制,需要更改。

标签: java paint histogram


【解决方案1】:

“但是当我尝试使用 fillRect 时,矩形是从上到下的。”

您需要考虑的一些事项。

  1. 水平线,例如,如果您的面板尺寸为 500,您会希望水平线类似于 450。所以让我们从它开始

    int horizon = 450;
    
  2. 您需要考虑每个数据栏的高度。要做到这一点,您需要一个增量,假设每个单位增量为 5 px。因此,要获得高度,请将单位数乘以增量量

    int increment = 5;
    ...
    int height = increment * units;
    
  3. 现在您需要做的就是从horizon 中减去height,您就有了yfillOval 起点

    int y = horizon - height
    

 0  +---------------------
    |
    |
    |
    |    +----+   horizon - height = 150 = y point for fillRect
    |    |    |
    |    |    |
    |    |    |
 y  |    |    |   height = 300
    |    |    |
    |    |    |
    |    |    |
    |----------------------  450 horizon
    |
    +----------------------  500

g.fillRect(x, y, width, height);

【讨论】:

  • 感谢您的帮助!你的画帮了大忙! :-)
【解决方案2】:

我建议旋转/平移 Graphics 对象:

Graphics2D graphics = (Graphics2D) g;
graphics.rotate(Math.PI, cx, cy);

其中 (cx, cy) 是绘图的中心。图形将围绕该中心旋转 180 度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 2018-04-03
    • 2012-09-13
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    相关资源
    最近更新 更多