Example usage for java.awt Graphics2D drawLine

List of usage examples for java.awt Graphics2D drawLine

Introduction

In this page you can find the example usage for java.awt Graphics2D drawLine.

Prototype

public abstract void drawLine(int x1, int y1, int x2, int y2);

Source Link

Document

Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system.

Usage

From source file:de._13ducks.cor.graphics.GraphicsComponent.java

@Override
public void paintComponent(Graphics g) {
    //Die echte, letzendlich gltige paint-Methode, sollte nicht direkt aufgerufen werden
    // verwendet advanced Grafiktechniken, also Graphics2D Api verwenden
    Graphics2D g2 = (Graphics2D) g;
    if (modi == 2) {
        g2.setColor(Color.BLACK);
        // Editor
        // Bodentexturen rendern

        if (renderGround) {
            // OK, Boden rendern!
            runRenderRoundGround(g2);//from   www.  j a  va  2 s. com
        }
        // Mesh rendern?
        if (renderMesh) {
            g2.setColor(Color.BLACK);
            // Mesh rendern
            for (int i = 0; i < sizeX; i++) {
                //Am oberen Rand entlanggehen, linie nach Rechts unten zeichnen
                int startX = i;
                int startY = 0;
                g2.drawLine((startX * 20) + 5, startY * 15, (sizeX * 20) + 5, ((sizeX - startX)) * 15);

                //Am oberen Rand entlanggehen, linie nach Links unten zeichnen
                g2.drawLine((startX * 20) - 10, startY * 15, -10, ((startX)) * 15);
            }

            for (int i = 0; i < sizeY; i++) {
                //Am linken Rand entlang gehen. Line nach rechts unten ziehen
                int startX = 0;
                int startY = i;

                g2.drawLine(startX * 20, (startY * 15) + 25, (sizeY - i) * 20, (sizeY * 15) + 25);
            }
        }
        if (renderBuildings) {
            // Gebude
            renderBuildings(g2);
        }

        if (renderCursor) {
            //Cursor rendern
            renderCursor(g2);
        }

        if (renderObjects) {
            // Feste Objekte
            runRenderRoundFix(g2);
        }

        if (renderCreeps) {
            // Einheiten
            renderUnits(g2);
        }
        if (renderPicCursor) {
            // Nochmal, damit es ber Einheiten schwebt (naja, leichter Pfusch)
            renderCursor(g2);
        }

    } else if (modi == 4) {
        // Debug-zeichnen
        paint_debug(g2);
    }
}

From source file:org.messic.server.facade.controllers.pages.CaptchaController.java

@ApiMethod(path = "/captcha", verb = ApiVerb.GET, description = "Get a captcha", produces = {
        MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
@ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error") })
@RequestMapping(value = "", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)/*from   w  w  w.ja v  a 2  s .  co m*/
@ResponseBody
@ApiResponseObject
public Captcha getCaptcha() throws UnknownMessicRESTException {

    try {
        UUID idOne = UUID.randomUUID();
        // create the image with the text
        BufferedImage bi = service.getImageChallengeForID(idOne.toString());
        BufferedImage bi2 = Util.ImagedeepCopy(bi);
        Graphics2D g2d = (Graphics2D) bi.getGraphics();
        float alpha = 0.25f;
        int type = AlphaComposite.SRC_OVER;
        AlphaComposite composite = AlphaComposite.getInstance(type, alpha);
        g2d.setComposite(composite);

        final int Min = 5;
        final int Max = 30;
        int random1 = Min + (int) (Math.random() * ((Max - Min) + 1));
        int random2 = Min + (int) (Math.random() * ((Max - Min) + 1));

        g2d.drawImage(bi2, random1, random2, null);

        alpha = 0.80f;
        type = AlphaComposite.SRC_OVER;
        composite = AlphaComposite.getInstance(type, alpha);
        g2d.setComposite(composite);

        int MinX = 0;
        int MaxX = bi.getWidth();
        int MinY = 0;
        int MaxY = bi.getHeight();
        g2d.setColor(Color.black);
        for (int i = 0; i < random2; i++) {
            int random3 = MinX + (int) (Math.random() * ((MaxX - MinX) + 1));
            int random4 = MinX + (int) (Math.random() * ((MaxX - MinX) + 1));
            int random5 = MinY + (int) (Math.random() * ((MaxY - MinY) + 1));
            int random6 = MinY + (int) (Math.random() * ((MaxY - MinY) + 1));
            g2d.drawLine(random3, random5, random4, random6);
        }

        Captcha result = new Captcha();
        result.id = idOne.toString();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bi, "jpg", baos);
        byte[] resultb64 = Base64.encode(baos.toByteArray());
        result.captchaImage = new String(resultb64);
        return result;
    } catch (Exception e) {
        throw new UnknownMessicRESTException(e);
    }
}

From source file:savant.view.swing.Ruler.java

/**
 * Render the background of this graphpane
 * @param g The graphics object to use// w w w  . j a v a 2 s.com
 */
private void renderBackground(Graphics g) {

    Graphics2D g2 = (Graphics2D) g;

    try {

        Image image = javax.imageio.ImageIO
                .read(getClass().getResource("/savant/images/bar_selected_glossy.png"));
        Composite originalComposite = ((Graphics2D) g).getComposite();
        ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.85F));
        g.drawImage(image, -getWidth(), 0, getWidth() * 3, getHeight(), this);
        ((Graphics2D) g).setComposite(originalComposite);
    } catch (Exception e) {
        LOG.error("Error drawing image background");
    }

    Range r = locationController.getRange();

    // At early points in the GUI initialisation, the range has not yet been set.
    if (r == null) {
        return;
    }

    int[] tickPositions = MiscUtils.getTickPositions(r);
    int separation = tickPositions.length > 1 ? tickPositions[1] - tickPositions[0] : 0;
    int xEnd = Integer.MIN_VALUE;
    FontMetrics fm = g2.getFontMetrics();

    for (int p : tickPositions) {

        int x = MiscUtils.transformPositionToPixel(p, getWidth(), r);
        if (x > xEnd + 10) {
            g2.setColor(new Color(50, 50, 50, 50)); //BrowserDefaults.colorAxisGrid);
            g2.drawLine(x, 0, x, getHeight());

            String numStr = MiscUtils.posToShortStringWithSeparation(p, separation);
            g2.setColor(Color.black);
            g2.drawString(numStr, x + 3, getHeight() / 2 + 3);
            xEnd = x + fm.stringWidth(numStr) + 3;
        }
    }

    if (r.getLength() >= locationController.getRangeStart()) {
        try {
            Image image_left_cap = javax.imageio.ImageIO
                    .read(getClass().getResource("/savant/images/round_cap_left_bordered.png"));
            int pos = getLeftCapPos();
            g.drawImage(image_left_cap, pos, 0, CAP_WIDTH, CAP_HEIGHT, this);
            g.setColor(Savant.getInstance().getBackground());
            g.fillRect(pos, 0, -getWidth(), getHeight());
        } catch (IOException ex) {
            LOG.error("Drawing failed.", ex);
        }
    }

    if (r.getLength() >= locationController.getMaxRangeEnd() - locationController.getRangeEnd()) {
        try {
            Image image_right_cap = javax.imageio.ImageIO
                    .read(getClass().getResource("/savant/images/round_cap_right_bordered.png"));
            int pos = MiscUtils.transformPositionToPixel(locationController.getMaxRangeEnd(), getWidth(),
                    locationController.getRange());
            g.drawImage(image_right_cap, pos - CAP_WIDTH, 0, CAP_WIDTH, CAP_HEIGHT, this);
            g.setColor(Savant.getInstance().getBackground());
            g.fillRect(pos, 0, this.getWidth(), this.getHeight());

        } catch (IOException ex) {
            LOG.error("Drawing failed.", ex);
        }
    }
}

From source file:biogenesis.Organism.java

public BufferedImage getImage() {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = image.createGraphics();
    g.setBackground(Color.BLACK);
    g.clearRect(0, 0, width, height);/*  w  w  w. j  ava 2s.com*/
    for (int i = _segments - 1; i >= 0; i--) {
        g.setColor(_segColor[i]);
        g.drawLine(x1[i] - x + _centerX, y1[i] - y + _centerY, x2[i] - x + _centerX, y2[i] - y + _centerY);
    }
    return image;
}

From source file:nl.b3p.kaartenbalie.core.server.b3pLayering.ConfigLayer.java

protected void drawTitledMessageBox(Graphics2D g2d, String title, String message, int x, int y, int w, int h) {
    /* Do some calculations and init variables. */
    g2d.setFont(KBConfiguration.OHD_messageBoxFont);
    FontMetrics fm = g2d.getFontMetrics();
    int labelHeight = KBConfiguration.OHD_messageBoxFont.getSize() + (KBConfiguration.OHD_padding * 2);
    int angling = labelHeight;
    Rectangle2D testRectangle = fm.getStringBounds(title, g2d);
    int labelWidth = (int) testRectangle.getWidth();

    if (w < labelWidth + (2 * angling)) {
        w = labelWidth + (2 * angling);//from   w  w w  . ja v  a 2 s. c o  m
    }
    y += labelHeight;
    /* Now draw the box...    */
    drawMessageBox(g2d, message, x, y, w, h);

    /* Draw the label background */
    g2d.setColor(KBConfiguration.OHD_labelBoxColor);
    GeneralPath label = new GeneralPath();
    label.moveTo(x, y);
    label.lineTo(x + angling, y - labelHeight);
    label.lineTo(x + angling + labelWidth, y - labelHeight);
    label.lineTo(x + (angling * 2) + labelWidth, y);
    label.closePath();
    g2d.fill(label);

    /* Draw the label Lines..  */
    g2d.setColor(KBConfiguration.OHD_borderBoxTopLeft);
    g2d.drawLine(x, y, x + angling, y - labelHeight);
    g2d.drawLine(x + angling, y - labelHeight, x + angling + labelWidth, y - labelHeight);
    g2d.setColor(KBConfiguration.OHD_borderBoxBottomRight);
    g2d.drawLine(x + angling + labelWidth, y - labelHeight, x + (angling * 2) + labelWidth, y);
    g2d.setColor(KBConfiguration.OHD_borderBoxBackground);
    g2d.drawLine(x + (angling * 2) + labelWidth, y, x, y);
    /*Then add the title... */
    g2d.setColor(KBConfiguration.OHD_labelFontBoxColor);
    g2d.drawString(title, x + angling, y - KBConfiguration.OHD_padding);

}

From source file:org.squidy.designer.zoom.impl.PortShape.java

/**
 * @param paintContext/*from w w w  .j  a v  a2s.  c o  m*/
 */
private void paintCreatingEdge(PPaintContext paintContext) {

    // Get graphics to paint creating edge.
    Graphics2D g2d = paintContext.getGraphics();

    Stroke defaultStroke = g2d.getStroke();
    g2d.setColor(Color.GRAY);
    g2d.setStroke(STROKE_CREATING_EDGE);

    pointStart.setLocation(startX, startY);
    pointCurrent.setLocation(currentX, currentY);
    globalToLocal(pointStart);
    globalToLocal(pointCurrent);

    double x1 = pointStart.getX();
    double y1 = pointStart.getY();
    double x2 = pointCurrent.getX();
    double y2 = pointCurrent.getY();

    /*      
          double width = Math.abs(x1 - x2);
          double height = Math.abs(y1 - y2);
            
          int division = 2;
          double middleLeftX = x1 + (width / division);
          double middleLeftY = y1 + (height / division);
          double middleRightX = x2 - (width / division);
          double middleRightY = y2 - (height / division);
                  
          curve.setCurve(x1, y1, middleLeftX, middleLeftY, middleRightX, middleRightY, x2, y2);
    */

    //      double width = Math.abs(x1 - x2);
    //      curve.setCurve(x1, y1, x1 + (width / 2), y1, x2 - (width / 2), y2, x2, y2);
    //      g2d.draw(curve);

    g2d.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
    g2d.setStroke(defaultStroke);
}

From source file:at.tuwien.ifs.somtoolbox.apps.viewer.GeneralUnitPNode.java

/** @see edu.umd.cs.piccolo.PNode#paint(edu.umd.cs.piccolo.util.PPaintContext) */
@Override//from   www.ja  v a2 s.  c  om
protected void paint(PPaintContext paintContext) {
    Graphics2D g2d = paintContext.getGraphics();

    if (state.exactUnitPlacement && getMapPNode().getCurrentVisualization() == null) { // black background for sky
        // vis
        border.setRect(X, Y, width, height);
        g2d.setColor(Color.BLACK);
        g2d.fill(border);
    }

    if (drawBorder) {
        GridGeometry helper = state.growingSOM.getLayer().getGridGeometry();
        Vector3D[] v = helper.shapeLinePoints(X, Y, width, height);

        g2d.setStroke(borderStroke);
        g2d.setPaint(Color.CYAN);
        g2d.setColor(borderColor);
        g2d.drawLine((int) v[0].getX(), (int) v[0].getY(), (int) v[1].getX(), (int) v[1].getY());

        for (int i = 1; i < v.length; i++) {
            int i_1 = (i + 1) % v.length;
            g2d.drawLine((int) v[i].getX(), (int) v[i].getY(), (int) v[i_1].getX(), (int) v[i_1].getY());
        }

        border.setRect(helper.getBorder(X, Y, width, height));
    }

    PCamera pCam = paintContext.getCamera();
    if (!((PCanvas) pCam.getComponent()).getClass().equals(MapOverviewPane.MapOverviewCanvas.class)) { // only for
        // main
        // display
        currentScale = paintContext.getScale();
        if (currentScale != oldScale) {
            // System.out.println("SCALE: "+currentScale);
            // double os = t10.getScale();
            // t10.setScale(1/currentScale);
            // if (t10.getGlobalFullBounds().width>this.width) {
            // t10.setScale(os);
            // }

            if (currentScale < state.scaleLimits[1]) { // no information
                if (currentDetailLevel != DETAIL_LEVEL_NO) {
                    currentDetailLevel = DETAIL_LEVEL_NO;
                    detailChanged();
                }
            } else if (currentScale >= state.scaleLimits[1] && currentScale < state.scaleLimits[2]) { // little
                // information
                if (currentDetailLevel != DETAIL_LEVEL_LOW) {
                    currentDetailLevel = DETAIL_LEVEL_LOW;
                    detailChanged();
                }
            } else if (currentScale >= state.scaleLimits[2] && currentScale < state.scaleLimits[3]) { // more labels
                if (currentDetailLevel != DETAIL_LEVEL_MEDIUM) {
                    currentDetailLevel = DETAIL_LEVEL_MEDIUM;
                    detailChanged();
                }
            } else if (currentScale >= state.scaleLimits[3]) { // detailed information
                if (currentDetailLevel != DETAIL_LEVEL_HIGH) {
                    currentDetailLevel = DETAIL_LEVEL_HIGH;
                    detailChanged();
                }
            }

            oldScale = currentScale;
        }
    }
}

From source file:ucar.unidata.idv.control.chart.RangeFilter.java

/**
 * Draws the annotation.// w ww .  ja  v a 2  s  .  c  om
 *
 * @param g2  the graphics device.
 * @param plot  the plot.
 * @param dataArea  the data area.
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param rendererIndex  the renderer index.
 * @param info  an optional info object that will be populated with
 *              entity information.
 */
public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis,
        int rendererIndex, PlotRenderingInfo info) {
    super.setGraphicsState(g2);
    if (!getPlotWrapper().okToDraw(this)) {
        return;
    }
    g2.setStroke(new BasicStroke());
    boolean selected = getSelected();
    if (attached != null) {
        selected |= attached.getSelected();
    }

    if (selected) {
        g2.setColor(COLOR_SELECTED);
    } else {
        g2.setColor(getColor());
    }
    y = (int) rangeAxis.valueToJava2D(rangeValue, dataArea, RectangleEdge.LEFT);

    int width = (int) ANNOTATION_WIDTH;
    int width2 = (int) (ANNOTATION_WIDTH / 2);
    x = (int) dataArea.getX();
    //        System.err.println("x/y:" + x +"/" +y);

    int[] xs;
    int[] ys;
    if (type == TYPE_LESSTHAN) {
        xs = new int[] { x, x + width, x + width2, x };
        ys = new int[] { y, y, y + width, y };
    } else {
        xs = new int[] { x, x + width, x + width2, x };
        ys = new int[] { y, y, y - width, y };

    }
    g2.fillPolygon(xs, ys, xs.length);

    g2.setColor(Color.gray);
    g2.drawLine(x + width, y, (int) (dataArea.getX() + dataArea.getWidth()), y);

    if ((attached != null) && (type == TYPE_LESSTHAN)) {
        int otherY = (int) rangeAxis.valueToJava2D(attached.rangeValue, dataArea, RectangleEdge.LEFT);

        g2.drawLine(x + width2, y + width, x + width2, otherY - width);
    }
}

From source file:com.igormaznitsa.mindmap.swing.panel.MindMapPanel.java

private static void drawBackground(final Graphics2D g, final MindMapPanelConfig cfg) {
    final Rectangle clipBounds = g.getClipBounds();

    if (cfg.isDrawBackground()) {
        g.setColor(cfg.getPaperColor());
        g.fillRect(clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height);

        if (cfg.isShowGrid()) {
            final double scaledGridStep = cfg.getGridStep() * cfg.getScale();

            final float minX = clipBounds.x;
            final float minY = clipBounds.y;
            final float maxX = clipBounds.x + clipBounds.width;
            final float maxY = clipBounds.y + clipBounds.height;

            g.setColor(cfg.getGridColor());

            for (float x = 0.0f; x < maxX; x += scaledGridStep) {
                if (x < minX) {
                    continue;
                }/*  w  w  w . ja  v a  2s. c o m*/
                final int intx = Math.round(x);
                g.drawLine(intx, (int) minY, intx, (int) maxY);
            }

            for (float y = 0.0f; y < maxY; y += scaledGridStep) {
                if (y < minY) {
                    continue;
                }
                final int inty = Math.round(y);
                g.drawLine((int) minX, inty, (int) maxX, inty);
            }
        }
    }
}

From source file:de.codesourcery.planning.swing.DateAxis.java

public BoundingBox render(ITimelineCallback callback, boolean layoutOnly) {
    final Calendar cal = Calendar.getInstance();
    cal.setTime(startDate);/*  w  w  w .  java  2 s .c om*/
    cal.set(Calendar.MILLISECOND, 0);
    Date currentDate = cal.getTime();

    final Date endDate = duration.addTo(startDate);

    BoundingBox lastLabel = null;

    final int labelSpacing = 10;

    final Graphics2D graphics = callback.getGraphics();
    final int fontHeight = graphics.getFontMetrics().getHeight();

    final double scalingFactor = getXScalingFactor(callback.getBoundingBox());
    final BoundingBox box = callback.getBoundingBox();
    double x = callback.getBoundingBox().getX();
    final int tickToLabelSpacing = 2;
    final int tickLength = fontHeight;
    final int axisHeight = fontHeight + tickLength + tickToLabelSpacing;
    final double xIncrement = Math.floor(tickDuration.toSeconds() * scalingFactor);

    final Color oldColor = graphics.getColor();
    //      
    while (currentDate.compareTo(endDate) <= 0) {
        final int currentX = (int) Math.floor(x);
        if (lastLabel == null || lastLabel.getMaxX() < x) {
            final String labelText = callback.getLabelProvider().getTimelineLabel(currentDate);
            if (!StringUtils.isBlank(labelText)) {
                final Rectangle2D stringBounds = callback.getStringBounds(labelText);

                if (!layoutOnly) {
                    graphics.setColor(Color.BLACK);
                    // draw tick
                    final Stroke oldStroke = graphics.getStroke();
                    graphics.setStroke(new BasicStroke(2.0f));
                    graphics.drawLine(currentX, box.getY() + axisHeight, currentX,
                            box.getY() + fontHeight + tickToLabelSpacing);
                    graphics.setStroke(oldStroke);

                    // draw label
                    callback.drawString(Color.BLACK, currentX, box.getY(), labelText);
                }

                final BoundingBox labelBox = new BoundingBox(currentX, box.getY(),
                        currentX + (int) stringBounds.getWidth() + labelSpacing,
                        box.getY() + (int) stringBounds.getHeight());

                if (lastLabel == null) {
                    lastLabel = labelBox;
                } else {
                    lastLabel.add(labelBox);
                }

            }
        } else {
            // draw short tick
            if (!layoutOnly) {

                final int halfTickHeight = (int) Math.floor(tickLength / 2.0d);

                graphics.drawLine(currentX, box.getY() + axisHeight, currentX,
                        box.getY() + axisHeight - halfTickHeight);
            }
        }

        // draw part of axis
        if (!layoutOnly) {
            graphics.drawLine((int) x, box.getY() + axisHeight, (int) (x + xIncrement),
                    box.getY() + axisHeight);
        }
        x += xIncrement;
        currentDate = tickDuration.addTo(currentDate);
    }

    callback.getGraphics().setColor(oldColor);
    final BoundingBox result = lastLabel != null ? lastLabel : new BoundingBox(0, 0, 0, 0);
    result.incHeight(axisHeight);
    return result;
}