Search code examples
javagraphics2dpolyline

Java Graphics 2d avoid Polyline distorted corners


i'm working on a graphic interface for drawing subway maps. A line is represented with station as circles and a polyline to link them.You can move the stations with a mouseDrag and of course it updates the displaying map in real time. My problem is when stations comes to a certain angle, there is a polyline distortion and the corner created by the 2 lines is out of the station circle display, i'd like to know if there is a way to avoid this.

screenshots of the app with the polyline issue

here's my code for the polyline's draw

//x and y point array creation
    xPoints = new int[this.stationViews.size()];
    yPoints = new int[this.stationViews.size()];
    for (int i=0;i<this.stationViews.size();i++) {
        //fill arrays with the center point of circles representing stations
        xPoints[i] = this.stationViews.get(i).getStation().getPosX()-this.stationViews.size()/2;
        yPoints[i] = this.stationViews.get(i).getStation().getPosY()-this.stationViews.size();
    }

    //setting color
    g2D.setColor(this.line.getColor());

    //set stroke width relative to the zoom level
    int strokeWidth=5;
    if(!this.stationViews.isEmpty()) {
    if (this.stationViews.get(0).getStationSize()>14) {
        strokeWidth = this.stationViews.get(0).getStationSize()-13;
    }else {
        strokeWidth = 3;
    }
    } 
    g2D.setStroke(new BasicStroke(strokeWidth));



    //draw the polyline
    if (this.stationViews.size() >1) {
    g2D.drawPolyline(xPoints, yPoints, this.stationViews.size());
    }
    //draw the station (g2D.drawCircle)
    for (StationView stationView : stationViews) {
        stationView.affiche(g2D,this.line.getColor());
    }

thank you for your help


Solution

  • That is called the miter. You seem to be per default using JOIN_MITER, sharp joining of extended lines at the end, which can point far out of the join for small angles.

    g2d.setStroke(new BasicStroke(strokeWidth,
        BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 5));
    

    miter a surface forming the beveled end or edge of a piece where a joint is made by cutting two pieces at an angle and fitting them together.

    It is also a bishop's cap with a pointy top, hence the name.