Example usage for java.awt.geom AffineTransform AffineTransform

List of usage examples for java.awt.geom AffineTransform AffineTransform

Introduction

In this page you can find the example usage for java.awt.geom AffineTransform AffineTransform.

Prototype

public AffineTransform() 

Source Link

Document

Constructs a new AffineTransform representing the Identity transformation.

Usage

From source file:MainClass.java

public void paintToPDF(JTextPane ta) {
    try {//  w ww.  ja  v  a  2s .  c om
        ta.setBounds(0, 0, (int) convertToPixels(612 - 58), (int) convertToPixels(792 - 60));

        Document document = new Document();
        FileOutputStream fos = new FileOutputStream("2.pdf");
        PdfWriter writer = PdfWriter.getInstance(document, fos);

        document.setPageSize(new com.lowagie.text.Rectangle(612, 792));
        document.open();
        PdfContentByte cb = writer.getDirectContent();

        cb.saveState();
        cb.concatCTM(1, 0, 0, 1, 0, 0);

        DefaultFontMapper mapper = new DefaultFontMapper();
        mapper.insertDirectory("c:/windows/fonts");

        Graphics2D g2 = cb.createGraphics(612, 792, mapper, true, .95f);

        AffineTransform at = new AffineTransform();
        at.translate(convertToPixels(20), convertToPixels(20));
        at.scale(pixelToPoint, pixelToPoint);

        g2.transform(at);

        g2.setColor(Color.WHITE);
        g2.fill(ta.getBounds());

        Rectangle alloc = getVisibleEditorRect(ta);
        ta.getUI().getRootView(ta).paint(g2, alloc);

        g2.setColor(Color.BLACK);
        g2.draw(ta.getBounds());

        g2.dispose();
        cb.restoreState();
        document.close();
        fos.flush();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.fop.render.pdf.PDFImageHandlerSVG.java

/** {@inheritDoc} */
public void handleImage(RenderingContext context, // CSOK: MethodLength
        Image image, Rectangle pos) throws IOException {
    PDFRenderingContext pdfContext = (PDFRenderingContext) context;
    PDFContentGenerator generator = pdfContext.getGenerator();
    ImageXMLDOM imageSVG = (ImageXMLDOM) image;

    FOUserAgent userAgent = context.getUserAgent();
    final float deviceResolution = userAgent.getTargetResolution();
    if (log.isDebugEnabled()) {
        log.debug("Generating SVG at " + deviceResolution + "dpi.");
    }/* w ww. ja v  a2 s.  c  o m*/

    final float uaResolution = userAgent.getSourceResolution();
    SVGUserAgent ua = new SVGUserAgent(userAgent, new AffineTransform());

    GVTBuilder builder = new GVTBuilder();

    //Controls whether text painted by Batik is generated using text or path operations
    boolean strokeText = false;
    //TODO connect with configuration elsewhere.

    BridgeContext ctx = new PDFBridgeContext(ua, (strokeText ? null : pdfContext.getFontInfo()),
            userAgent.getFactory().getImageManager(), userAgent.getImageSessionContext(),
            new AffineTransform());

    //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine)
    //to it.
    Document clonedDoc = BatikUtil.cloneSVGDocument(imageSVG.getDocument());

    GraphicsNode root;
    try {
        root = builder.build(ctx, clonedDoc);
        builder = null;
    } catch (Exception e) {
        SVGEventProducer eventProducer = SVGEventProducer.Provider
                .get(context.getUserAgent().getEventBroadcaster());
        eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI());
        return;
    }
    // get the 'width' and 'height' attributes of the SVG document
    float w = image.getSize().getWidthMpt();
    float h = image.getSize().getHeightMpt();

    float sx = pos.width / w;
    float sy = pos.height / h;

    //Scaling and translation for the bounding box of the image
    AffineTransform scaling = new AffineTransform(sx, 0, 0, sy, pos.x / 1000f, pos.y / 1000f);
    double sourceScale = UnitConv.IN2PT / uaResolution;
    scaling.scale(sourceScale, sourceScale);

    //Scale for higher resolution on-the-fly images from Batik
    AffineTransform resolutionScaling = new AffineTransform();
    double targetScale = uaResolution / deviceResolution;
    resolutionScaling.scale(targetScale, targetScale);
    resolutionScaling.scale(1.0 / sx, 1.0 / sy);

    //Transformation matrix that establishes the local coordinate system for the SVG graphic
    //in relation to the current coordinate system
    AffineTransform imageTransform = new AffineTransform();
    imageTransform.concatenate(scaling);
    imageTransform.concatenate(resolutionScaling);

    if (log.isTraceEnabled()) {
        log.trace("nat size: " + w + "/" + h);
        log.trace("req size: " + pos.width + "/" + pos.height);
        log.trace("source res: " + uaResolution + ", targetRes: " + deviceResolution + " --> target scaling: "
                + targetScale);
        log.trace(image.getSize());
        log.trace("sx: " + sx + ", sy: " + sy);
        log.trace("scaling: " + scaling);
        log.trace("resolution scaling: " + resolutionScaling);
        log.trace("image transform: " + resolutionScaling);
    }

    /*
     * Clip to the svg area.
     * Note: To have the svg overlay (under) a text area then use
     * an fo:block-container
     */
    if (log.isTraceEnabled()) {
        generator.comment("SVG setup");
    }
    generator.saveGraphicsState();
    if (context.getUserAgent().isAccessibilityEnabled()) {
        MarkedContentInfo mci = pdfContext.getMarkedContentInfo();
        generator.beginMarkedContentSequence(mci.tag, mci.mcid);
    }
    generator.updateColor(Color.black, false, null);
    generator.updateColor(Color.black, true, null);

    if (!scaling.isIdentity()) {
        if (log.isTraceEnabled()) {
            generator.comment("viewbox");
        }
        generator.add(CTMHelper.toPDFString(scaling, false) + " cm\n");
    }

    //SVGSVGElement svg = ((SVGDocument)doc).getRootElement();

    PDFGraphics2D graphics = new PDFGraphics2D(true, pdfContext.getFontInfo(), generator.getDocument(),
            generator.getResourceContext(), pdfContext.getPage().referencePDF(), "", 0);
    graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());

    if (!resolutionScaling.isIdentity()) {
        if (log.isTraceEnabled()) {
            generator.comment("resolution scaling for " + uaResolution + " -> " + deviceResolution);
        }
        generator.add(CTMHelper.toPDFString(resolutionScaling, false) + " cm\n");
        graphics.scale(1.0 / resolutionScaling.getScaleX(), 1.0 / resolutionScaling.getScaleY());
    }

    if (log.isTraceEnabled()) {
        generator.comment("SVG start");
    }

    //Save state and update coordinate system for the SVG image
    generator.getState().save();
    generator.getState().concatenate(imageTransform);

    //Now that we have the complete transformation matrix for the image, we can update the
    //transformation matrix for the AElementBridge.
    PDFAElementBridge aBridge = (PDFAElementBridge) ctx.getBridge(SVGDOMImplementation.SVG_NAMESPACE_URI,
            SVGConstants.SVG_A_TAG);
    aBridge.getCurrentTransform().setTransform(generator.getState().getTransform());

    graphics.setPaintingState(generator.getState());
    graphics.setOutputStream(generator.getOutputStream());
    try {
        root.paint(graphics);
        ctx.dispose();
        generator.add(graphics.getString());
    } catch (Exception e) {
        SVGEventProducer eventProducer = SVGEventProducer.Provider
                .get(context.getUserAgent().getEventBroadcaster());
        eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI());
    }
    generator.getState().restore();
    if (context.getUserAgent().isAccessibilityEnabled()) {
        generator.restoreGraphicsStateAccess();
    } else {
        generator.restoreGraphicsState();
    }
    if (log.isTraceEnabled()) {
        generator.comment("SVG end");
    }
}

From source file:ArrowIcon.java

protected Image getArrowImage() {
    if (arrowImage == null) {
        arrowImage = createTranslucentImage(size, size);
        AffineTransform atx = direction != SOUTH ? new AffineTransform() : null;
        switch (direction) {
        case NORTH:
            atx.setToRotation(Math.PI, size / 2, size / 2);
            break;
        case EAST:
            atx.setToRotation(-(Math.PI / 2), size / 2, size / 2);
            break;
        case WEST:
            atx.setToRotation(Math.PI / 2, size / 2, size / 2);
        case SOUTH:
        default: {
            /* no xform*/ }
        }//from  w ww. j a v  a  2s. co  m
        Graphics2D ig = (Graphics2D) arrowImage.getGraphics();
        if (atx != null) {
            ig.setTransform(atx);
        }
        int width = size;
        int height = size / 2 + 1;
        int xx = (size - width) / 2;
        int yy = (size - height + 1) / 2;

        Color base = color != null ? color : UIManager.getColor("controlDkShadow").darker();

        paintArrow(ig, base, xx, yy);
        paintArrowBevel(ig, base, xx, yy);
        paintArrowBevel(ig, deriveColorHSB(base, 0f, 0f, .20f), xx, yy + 1);
    }
    return arrowImage;
}

From source file:org.apache.pdfbox.pdmodel.font.PDSimpleFont.java

/**
 * {@inheritDoc}/*  www .  j  a va 2  s .  c om*/
 */
public void drawString(String string, int[] codePoints, Graphics g, float fontSize, AffineTransform at, float x,
        float y) throws IOException {
    Font awtFont = getawtFont();
    FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);
    GlyphVector glyphs = null;
    boolean useCodepoints = codePoints != null && isType0Font();
    PDFont descendantFont = useCodepoints ? ((PDType0Font) this).getDescendantFont() : null;
    // symbolic fonts may trigger the same fontmanager.so/dll error as described below
    if (useCodepoints && !descendantFont.getFontDescriptor().isSymbolic()) {
        PDCIDFontType2Font cid2Font = null;
        if (descendantFont instanceof PDCIDFontType2Font) {
            cid2Font = (PDCIDFontType2Font) descendantFont;
        }
        if ((cid2Font != null && cid2Font.hasCIDToGIDMap()) || isFontSubstituted) {
            // we still have to use the string if a CIDToGIDMap is used 
            glyphs = awtFont.createGlyphVector(frc, string);
        } else {
            glyphs = awtFont.createGlyphVector(frc, codePoints);
        }
    } else {
        // mdavis - fix fontmanager.so/dll on sun.font.FileFont.getGlyphImage
        // for font with bad cmaps?
        // Type1 fonts are not affected as they don't have cmaps
        if (!isType1Font() && awtFont.canDisplayUpTo(string) != -1) {
            LOG.warn("Changing font on <" + string + "> from <" + awtFont.getName() + "> to the default font");
            awtFont = Font.decode(null).deriveFont(1f);
        }
        glyphs = awtFont.createGlyphVector(frc, string);
    }
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    writeFont(g2d, at, x, y, glyphs);
}

From source file:org.apache.fop.render.intermediate.AbstractIFPainter.java

private AffineTransform combine(AffineTransform[] transforms) {
    AffineTransform at = new AffineTransform();
    for (int i = 0, c = transforms.length; i < c; i++) {
        at.concatenate(transforms[i]);//from w  ww  .  j ava 2 s.  c  om
    }
    return at;
}

From source file:org.jcurl.core.model.CurveManager.java

/**
 * Internal. Compute one rock curve segment and don't change internal state.
 * /*from ww  w.j a  v  a  2s.c  o m*/
 * @param i
 *            which rock
 * @param t0
 *            starttime
 * @return the new Curve in world coordinates.
 */
R1RNFunction doComputeCurve(final int i, final double t0, final PositionSet p, final SpeedSet s) {
    final Rock x = p.getRock(i);
    final Rock v = s.getRock(i);
    final R1RNFunction wc;
    if (v.distanceSq(0, 0) == 0)
        wc = SlideBase.still(x);
    else
        // FIXME add stop detection! Either here or in each slider?
        wc = new CurveTransformed(slider.computeRc(x, v),
                CurveTransformed.createRc2Wc(new AffineTransform(), x, v), t0);
    if (log.isDebugEnabled())
        log.debug(i + " " + wc);
    return wc;
}

From source file:org.apache.fop.render.pcl.PCLImageHandlerGraphics2D.java

/** {@inheritDoc} */
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException {
    PCLRenderingContext pclContext = (PCLRenderingContext) context;
    ImageGraphics2D imageG2D = (ImageGraphics2D) image;
    Dimension imageDim = imageG2D.getSize().getDimensionMpt();
    PCLGenerator gen = pclContext.getPCLGenerator();

    Point2D transPoint = pclContext.transformedPoint(pos.x, pos.y);
    gen.setCursorPos(transPoint.getX(), transPoint.getY());

    boolean painted = false;
    ByteArrayOutputStream baout = new ByteArrayOutputStream();
    PCLGenerator tempGen = new PCLGenerator(baout, gen.getMaximumBitmapResolution());
    tempGen.setDitheringQuality(gen.getDitheringQuality());
    try {//from w ww  .j  av  a 2  s.c o  m
        GraphicContext ctx = (GraphicContext) pclContext.getGraphicContext().clone();

        AffineTransform prepareHPGL2 = new AffineTransform();
        prepareHPGL2.scale(0.001, 0.001);
        ctx.setTransform(prepareHPGL2);

        PCLGraphics2D graphics = new PCLGraphics2D(tempGen);
        graphics.setGraphicContext(ctx);
        graphics.setClippingDisabled(false /*pclContext.isClippingDisabled()*/);
        Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, imageDim.getWidth(), imageDim.getHeight());
        imageG2D.getGraphics2DImagePainter().paint(graphics, area);

        //If we arrive here, the graphic is natively paintable, so write the graphic
        gen.writeCommand(
                "*c" + gen.formatDouble4(pos.width / 100f) + "x" + gen.formatDouble4(pos.height / 100f) + "Y");
        gen.writeCommand("*c0T");
        gen.enterHPGL2Mode(false);
        gen.writeText("\nIN;");
        gen.writeText("SP1;");
        //One Plotter unit is 0.025mm!
        double scale = imageDim.getWidth() / UnitConv.mm2pt(imageDim.getWidth() * 0.025);
        gen.writeText("SC0," + gen.formatDouble4(scale) + ",0,-" + gen.formatDouble4(scale) + ",2;");
        gen.writeText("IR0,100,0,100;");
        gen.writeText("PU;PA0,0;\n");
        baout.writeTo(gen.getOutputStream()); //Buffer is written to output stream
        gen.writeText("\n");

        gen.enterPCLMode(false);
        painted = true;
    } catch (UnsupportedOperationException uoe) {
        log.debug(
                "Cannot paint graphic natively. Falling back to bitmap painting. Reason: " + uoe.getMessage());
    }

    if (!painted) {
        //Fallback solution: Paint to a BufferedImage
        FOUserAgent ua = context.getUserAgent();
        ImageManager imageManager = ua.getFactory().getImageManager();
        ImageRendered imgRend;
        try {
            imgRend = (ImageRendered) imageManager.convertImage(imageG2D,
                    new ImageFlavor[] { ImageFlavor.RENDERED_IMAGE }/*, hints*/);
        } catch (ImageException e) {
            throw new IOException("Image conversion error while converting the image to a bitmap"
                    + " as a fallback measure: " + e.getMessage());
        }

        gen.paintBitmap(imgRend.getRenderedImage(), new Dimension(pos.width, pos.height),
                pclContext.isSourceTransparencyEnabled());
    }
}

From source file:com.googlecode.jchav.chart.Chart.java

/**
 * Creates a PNG graphic for the given data as a thumbnail image.
 *
 * @param out the stream to write the PNG to.  The caller is responsible
 *  for closing the stream.// w  w  w . ja  v  a  2  s  . c o m
 * 
 * @throws IOException if there was a problem creating the chart.
 */
public void writeThumbnail(final OutputStream out) throws IOException {

    // Set up the transfomration:
    final AffineTransform xform = new AffineTransform();
    xform.scale(thumbnailScale, thumbnailScale);

    // Thanks to the almanac for this one:
    // http://javaalmanac.com/egs/java.awt.image/CreateTxImage.html?l=rel
    final AffineTransformOp op = new AffineTransformOp(xform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);

    // The thumbnail does not need so much chart chrome: you can't
    // read the axis and the title is given in the HTML, so removing
    // these elements means there's more space in the thumbnail for the data
    boolean thumbChrome = false;

    if (false == thumbChrome) {
        chart.setTitle((String) null);
        chart.clearSubtitles();
        chart.removeLegend();

        // Removing the axis completly looks just weird, so we just
        // remove the labels:

        chart.getCategoryPlot().getRangeAxis().setLabel(null);
        chart.getCategoryPlot().getRangeAxis().setTickLabelsVisible(true);
        chart.getCategoryPlot().getRangeAxis().setTickMarksVisible(true);
        chart.getCategoryPlot().getRangeAxis().setAxisLineVisible(true);

        //  To show up at a small scale, we need a good sized axis stroke:
        Stroke stroke = new BasicStroke(2f);
        chart.getCategoryPlot().getRangeAxis().setAxisLineStroke(stroke);
        chart.getCategoryPlot().getRangeAxis().setTickMarkStroke(stroke);

        chart.getCategoryPlot().getDomainAxis().setLabel(null);
        chart.getCategoryPlot().getDomainAxis().setTickLabelsVisible(false);
        chart.getCategoryPlot().getDomainAxis().setAxisLineVisible(true);
        chart.getCategoryPlot().getDomainAxis().setAxisLineStroke(stroke);
    }

    final BufferedImage fullsize = chart.createBufferedImage(width, height);

    Graphics2D g = fullsize.createGraphics();
    for (Decorator decorator : thumbnailDecorators) {
        decorator.decorate(g, this);
    }

    final BufferedImage thumbnail = op.filter(fullsize, null /*null means create the image for us*/);

    ChartUtilities.writeBufferedImageAsPNG(out, thumbnail);

}

From source file:D20140128.ApacheXMLGraphicsTest.TilingPatternExample.java

private void paintTileAlone(Graphics2D g2d) {
    AffineTransform at = new AffineTransform();
    at.translate(5, 5);/*from   ww  w .ja  va 2s  . c  o m*/
    g2d.drawRenderedImage(this.tile, at);
}

From source file:ScalingMethods.java

/**
 * Draws the picture five times, using the five different scaling
 * approaches described in the book. All five look the same, since
 * all are using default (nearest neighbor) filtering during the
 * scale operation./*from  w ww.j av  a  2s. c  o m*/
 */
public void paintComponent(Graphics g) {
    int x = PADDING;
    int y = PADDING;

    // Simplest approach
    g.drawImage(picture, x, y, scaleW, scaleH, null);

    // Subregion approach
    x += scaleW + PADDING;
    g.drawImage(picture, x, y, x + scaleW, y + scaleH, 0, 0, picture.getWidth(), picture.getHeight(), null);

    // Graphics2D.scale approach
    x += scaleW + PADDING;
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.translate(x, y);
    g2d.scale(SCALE_FACTOR, SCALE_FACTOR);
    g2d.drawImage(picture, 0, 0, null);
    g2d.dispose();

    // AffineTransform.scale approach
    x += scaleW + PADDING;
    g2d = (Graphics2D) g.create();
    AffineTransform at = new AffineTransform();
    at.translate(x, y);
    at.scale(SCALE_FACTOR, SCALE_FACTOR);
    g2d.drawImage(picture, at, null);
    g2d.dispose();

    // getScaledInstance() approach
    x += scaleW + PADDING;
    Image scaledImg = picture.getScaledInstance(scaleW, scaleH, Image.SCALE_DEFAULT);
    g.drawImage(scaledImg, x, y, null);
}