I am trying to draw the line in the middle. I tried different coordinates

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 05:22:40

问题


Here is my paintComponent which contains the coordinates

public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g; 
        g2.drawLine(-100,0,500,0);
        g2.drawLine(141,-500,141,500);
        g2.translate(getWidth()/2.0, getHeight()/2.0);
        g2.scale(1,-1);
        g2.rotate(45*Math.PI/180);
        Rectangle2D r = new Rectangle2D.Double(0,0,100,100);
        g2.fill(r);


回答1:


It's a bit of a cheat, but...

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g.create();
    g2.drawLine(getWidth() / 2, 0, getWidth() / 2, getHeight());
    g2.drawLine(0, getHeight() / 2, getWidth(), getHeight()/ 2);
    g2.translate(getWidth() / 2.0, (getHeight() / 2.0));
    g2.scale(1, -1);
    g2.rotate(45 * Math.PI / 180);
    Rectangle2D r = new Rectangle2D.Double(-50, -50, 100, 100);
    g2.fill(r);
    g2.dispose();
}

Basically, the origin point is now the center of the screen, so in order to draw the rectangle "centered" around the origin point, you need to adjust the x/y accordingly

Now, you also adjust the origin point by 50x50 instead, but then you'd need to change the anchor point around which the Graphics context is rotated to the center of the box

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g.create();
    g2.drawLine(getWidth() / 2, 0, getWidth() / 2, getHeight());
    g2.drawLine(0, getHeight() / 2, getWidth(), getHeight()/ 2);
    g2.translate((getWidth() / 2.0) - 50, (getHeight() / 2.0) - 50);
    g2.scale(1, -1);
    g2.rotate(45 * Math.PI / 180, 50, 50);
    Rectangle2D r = new Rectangle2D.Double(0, 0, 100, 100);
    g2.fill(r);
    g2.dispose();
}


来源:https://stackoverflow.com/questions/32774263/i-am-trying-to-draw-the-line-in-the-middle-i-tried-different-coordinates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!