Java Code Examples for java.awt.geom.AffineTransform#translate()

The following examples show how to use java.awt.geom.AffineTransform#translate() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public static void render( Graphics2D gc, GraphicsNode svgGraphicsNode, Dimension2D svgGraphicsSize, int centerX,
    int centerY, int width, int height, double angleRadians ) {
  double scaleX = width / svgGraphicsSize.getWidth();
  double scaleY = height / svgGraphicsSize.getHeight();

  AffineTransform affineTransform = new AffineTransform();
  if ( centerX != 0 || centerY != 0 ) {
    affineTransform.translate( centerX, centerY );
  }
  affineTransform.scale( scaleX, scaleY );
  if ( angleRadians != 0 ) {
    affineTransform.rotate( angleRadians );
  }
  affineTransform.translate( -svgGraphicsSize.getWidth() / 2, -svgGraphicsSize.getHeight() / 2 );

  svgGraphicsNode.setTransform( affineTransform );

  svgGraphicsNode.paint( gc );
}
 
Example 2
Source Project: SproutLife   File: ImageManager.java    License: MIT License 6 votes vote down vote up
public BufferedImage generateCenteredImage(int imageWidth, int imageHeight,
                                           Point2D.Double centerLocation,
                                           Image logoImage) {
    try {
        panelController.getInteractionLock().readLock().lock();
        if ( panelController.getScrollController().getVisibleRectangle().width == 0 ||
             panelController.getScrollController().getVisibleRectangle().height == 0 ) {
            return null;
        }
        BufferedImage image = new BufferedImage(imageWidth, imageHeight,
            BufferedImage.TYPE_INT_RGB);
        
        Rectangle2D.Double bounds = getRendererBounds(imageWidth, imageHeight, centerLocation);
        AffineTransform transform = new AffineTransform();
        transform.scale(panelController.getScrollController().getScalingZoomFactor(), panelController.getScrollController().getScalingZoomFactor());
        transform.translate(-bounds.getMinX(),-bounds.getMinY());
 
        paintImage(image, logoImage, transform);
        return image;
    }
    finally {
        panelController.getInteractionLock().readLock().unlock();
    }
}
 
Example 3
public void drawConditionalSequenceFlowIndicator(Line2D.Double line) {
  int horizontal = (int) (CONDITIONAL_INDICATOR_WIDTH * 0.7);
  int halfOfHorizontal = horizontal / 2;
  int halfOfVertical = CONDITIONAL_INDICATOR_WIDTH / 2;

  Polygon conditionalIndicator = new Polygon();
  conditionalIndicator.addPoint(0, 0);
  conditionalIndicator.addPoint(-halfOfHorizontal, halfOfVertical);
  conditionalIndicator.addPoint(0, CONDITIONAL_INDICATOR_WIDTH);
  conditionalIndicator.addPoint(halfOfHorizontal, halfOfVertical);

  AffineTransform transformation = new AffineTransform();
  transformation.setToIdentity();
  double angle = Math.atan2(line.y2 - line.y1, line.x2 - line.x1);
  transformation.translate(line.x1, line.y1);
  transformation.rotate((angle - Math.PI / 2d));

  AffineTransform originalTransformation = g.getTransform();
  g.setTransform(transformation);
  g.draw(conditionalIndicator);

  Paint originalPaint = g.getPaint();
  g.setPaint(CONDITIONAL_INDICATOR_COLOR);
  g.fill(conditionalIndicator);

  g.setPaint(originalPaint);
  g.setTransform(originalTransformation);
}
 
Example 4
/**
 * Draw arraw
 *
 * @param g Graphics2D
 * @param sP Start point
 * @param angle Angle
 */
public static void drawArraw(Graphics2D g, PointF sP, double angle) {
    GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD, 5);
    Rectangle.Float rect = new Rectangle.Float(-4, -4, 8, 8);
    PointF[] pt = new PointF[5];
    pt[0] = new PointF(rect.x, rect.y);
    pt[1] = new PointF(rect.x + rect.width, rect.y + (rect.height / 2));
    pt[2] = new PointF(rect.x, rect.y + rect.height);
    pt[3] = new PointF(rect.x + rect.width / 2, pt[1].Y);
    pt[4] = pt[0];
    path.moveTo(pt[0].X, pt[0].Y);
    for (int i = 1; i < 5; i++) {
        path.lineTo(pt[i].X, pt[i].Y);
    }

    AffineTransform tempTrans = g.getTransform();
    if (angle != 0) {
        //AffineTransform myTrans = new AffineTransform();         
        AffineTransform myTrans = (AffineTransform) tempTrans.clone();
        //myTrans.translate(tempTrans.getTranslateX() + sP.X, tempTrans.getTranslateY() + sP.Y);
        myTrans.translate(sP.X, sP.Y);
        double angle1 = angle - 90;
        myTrans.rotate(angle1 * Math.PI / 180);
        g.setTransform(myTrans);
    }
    path.closePath();
    g.fill(path);

    if (angle != 0) {
        g.setTransform(tempTrans);
    }
}
 
Example 5
Source Project: pumpernickel   File: RotateTransition2D.java    License: MIT License 5 votes vote down vote up
@Override
public Transition2DInstruction[] getInstructions(float progress,
		Dimension size) {
	if (type == OUT) {
		progress = 1 - progress;
	}
	AffineTransform transform = new AffineTransform();
	transform.translate(size.width / 2, size.height / 2);
	transform.scale(progress, progress);
	transform.rotate((1 - progress) * 6);
	transform.translate(-size.width / 2, -size.height / 2);

	return new ImageInstruction[] { new ImageInstruction(type == IN),
			new ImageInstruction(type != IN, transform, null) };
}
 
Example 6
/**
 * Paints the background of a text field.
 *
 * @param context SynthContext identifying the <code>JComponent</code> and
 *                <code>Region</code> to paint to
 * @param g       <code>Graphics</code> to paint to
 * @param x       X coordinate of the area to paint to
 * @param y       Y coordinate of the area to paint to
 * @param w       Width of the area to paint to
 * @param h       Height of the area to paint to
 */
public void paintTextFieldBackground(SynthContext context, Graphics g, int x, int y, int w, int h) {
    if (context.getComponent().getComponentOrientation().isLeftToRight()) {
        paintBackground(context, g, x, y, w, h, null);
    } else {
        AffineTransform transform = new AffineTransform();

        transform.translate(x, y);
        transform.scale(-1, 1);
        transform.translate(-w, 0);
        paintBackground(context, g, 0, 0, w, h, transform);
    }
}
 
Example 7
/**
 * Paints the background of a text field.
 *
 * @param context SynthContext identifying the <code>JComponent</code> and
 *        <code>Region</code> to paint to
 * @param g <code>Graphics</code> to paint to
 * @param x X coordinate of the area to paint to
 * @param y Y coordinate of the area to paint to
 * @param w Width of the area to paint to
 * @param h Height of the area to paint to
 */
public void paintTextFieldBackground(SynthContext context,
                                      Graphics g, int x, int y,
                                      int w, int h) {
    if (context.getComponent().getComponentOrientation().isLeftToRight()){
        paintBackground(context, g, x, y, w, h, null);
    } else {
        AffineTransform transform = new AffineTransform();
        transform.translate(x,y);
        transform.scale(-1, 1);
        transform.translate(-w,0);
        paintBackground(context, g, 0, 0, w, h, transform);
    }
}
 
Example 8
/**
 * Paints the background of a combo box.
 *
 * @param context SynthContext identifying the <code>JComponent</code> and
 *        <code>Region</code> to paint to
 * @param g <code>Graphics</code> to paint to
 * @param x X coordinate of the area to paint to
 * @param y Y coordinate of the area to paint to
 * @param w Width of the area to paint to
 * @param h Height of the area to paint to
 */
public void paintComboBoxBackground(SynthContext context,
                                    Graphics g, int x, int y,
                                    int w, int h) {
    if (context.getComponent().getComponentOrientation().isLeftToRight()){
        paintBackground(context, g, x, y, w, h, null);
    } else {
        AffineTransform transform = new AffineTransform();
        transform.translate(x,y);
        transform.scale(-1, 1);
        transform.translate(-w,0);
        paintBackground(context, g, 0, 0, w, h, transform);
    }
}
 
Example 9
Source Project: workcraft   File: VisualModelTransformer.java    License: MIT License 5 votes vote down vote up
public static void rotateSelection(VisualModel vm, double theta) {
    Rectangle2D selectionBB = getNodesCoordinateBox(vm.getSelection());
    if (selectionBB != null) {
        AffineTransform t = new AffineTransform();
        Point2D cp = new Point2D.Double(selectionBB.getCenterX(), selectionBB.getCenterY());

        t.translate(cp.getX(), cp.getY());
        t.rotate(theta);
        t.translate(-cp.getX(), -cp.getY());

        transformNodes(vm.getSelection(), t);
    }
}
 
Example 10
Source Project: JDKSourceCode1.8   File: SynthPainterImpl.java    License: MIT License 5 votes vote down vote up
/**
 * Paints the background of a combo box.
 *
 * @param context SynthContext identifying the <code>JComponent</code> and
 *        <code>Region</code> to paint to
 * @param g <code>Graphics</code> to paint to
 * @param x X coordinate of the area to paint to
 * @param y Y coordinate of the area to paint to
 * @param w Width of the area to paint to
 * @param h Height of the area to paint to
 */
public void paintComboBoxBackground(SynthContext context,
                                    Graphics g, int x, int y,
                                    int w, int h) {
    if (context.getComponent().getComponentOrientation().isLeftToRight()){
        paintBackground(context, g, x, y, w, h, null);
    } else {
        AffineTransform transform = new AffineTransform();
        transform.translate(x,y);
        transform.scale(-1, 1);
        transform.translate(-w,0);
        paintBackground(context, g, 0, 0, w, h, transform);
    }
}
 
Example 11
protected void addImage(Graphics2D graphics, ImageResult imageResult, MapViewport viewport) throws IOException {
	Rectangle screenArea = viewport.getScreenArea();
	ReferencedEnvelope worldBounds = viewport.getBounds();
	// convert map bounds to application bounds
	double printScale = screenArea.getWidth() / worldBounds.getWidth();
	if (tileScale < 0) {
		tileScale = printScale;
	}
	Envelope applicationBounds = new Envelope((worldBounds.getMinX()) * printScale, (worldBounds.getMaxX())
			* printScale, -(worldBounds.getMinY()) * printScale, -(worldBounds.getMaxY()) * printScale);
	Bbox imageBounds = imageResult.getRasterImage().getBounds();
	// find transform between image bounds and application bounds
	double tx = (imageBounds.getX() * printScale / tileScale - applicationBounds.getMinX());
	double ty = (imageBounds.getY() * printScale / tileScale - applicationBounds.getMinY());
	BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageResult.getImage()));
	double scaleX = imageBounds.getWidth() / image.getWidth() * printScale / tileScale;
	double scaleY = imageBounds.getHeight() / image.getHeight() * printScale / tileScale;
	AffineTransform transform = new AffineTransform();
	transform.translate(tx, ty);
	transform.scale(scaleX, scaleY);
	if (log.isDebugEnabled()) {
		log.debug("adding image, width=" + image.getWidth() + ",height=" + image.getHeight() + ",x=" + tx + ",y="
				+ ty);
	}
	// opacity
	log.debug("before drawImage");
	// create a copy to apply transform
	Graphics2D g = (Graphics2D) graphics.create();
	// apply opacity to image off-graphics to avoid interference with whatever opacity model is used by graphics
	BufferedImage opaqueCopy = makeOpaque(image);
	g.drawImage(opaqueCopy, transform, null);
	log.debug("after drawImage");
}
 
Example 12
public void init(Graphics2D g2d, Context ctx, Dimension dim) {
    int w = dim.width;
    int h = dim.height;
    AffineTransform at = new AffineTransform();
    at.translate(0.0, (h - (w*h)/(w + h*0.1)) / 2);
    at.shear(0.1, 0.0);
    g2d.transform(at);
    dim.setSize(scaleForTransform(at, dim));
}
 
Example 13
/**
 * Paints the border of a formatted text field.
 *
 * @param context SynthContext identifying the <code>JComponent</code> and
 *        <code>Region</code> to paint to
 * @param g <code>Graphics</code> to paint to
 * @param x X coordinate of the area to paint to
 * @param y Y coordinate of the area to paint to
 * @param w Width of the area to paint to
 * @param h Height of the area to paint to
 */
public void paintFormattedTextFieldBorder(SynthContext context,
                                  Graphics g, int x, int y,
                                  int w, int h) {
    if (context.getComponent().getComponentOrientation().isLeftToRight()){
        paintBorder(context, g, x, y, w, h, null);
    } else {
        AffineTransform transform = new AffineTransform();
        transform.translate(x,y);
        transform.scale(-1, 1);
        transform.translate(-w,0);
        paintBorder(context, g, 0, 0, w, h, transform);
    }
}
 
Example 14
/**
 * Paints the background of a formatted text field.
 *
 * @param context SynthContext identifying the <code>JComponent</code> and
 *        <code>Region</code> to paint to
 * @param g <code>Graphics</code> to paint to
 * @param x X coordinate of the area to paint to
 * @param y Y coordinate of the area to paint to
 * @param w Width of the area to paint to
 * @param h Height of the area to paint to
 */
public void paintFormattedTextFieldBackground(SynthContext context,
                                      Graphics g, int x, int y,
                                      int w, int h) {
    if (context.getComponent().getComponentOrientation().isLeftToRight()){
        paintBackground(context, g, x, y, w, h, null);
    } else {
        AffineTransform transform = new AffineTransform();
        transform.translate(x,y);
        transform.scale(-1, 1);
        transform.translate(-w,0);
        paintBackground(context, g, 0, 0, w, h, transform);
    }
}
 
Example 15
/**
 * This method calculates six m** values and a focusX value that
 * are used by the native fragment shader.  These techniques are
 * based on a whitepaper by Daniel Rice on radial gradient performance
 * (attached to the bug report for 6521533).  One can refer to that
 * document for the complete set of formulas and calculations, but
 * the basic goal is to compose a transform that will convert an
 * (x,y) position in device space into a "u" value that represents
 * the relative distance to the gradient focus point.  The resulting
 * value can be used to look up the appropriate color by linearly
 * interpolating between the two nearest colors in the gradient.
 */
private static void setRadialGradientPaint(RenderQueue rq,
                                           SunGraphics2D sg2d,
                                           RadialGradientPaint paint,
                                           boolean useMask)
{
    boolean linear =
        (paint.getColorSpace() == ColorSpaceType.LINEAR_RGB);
    int cycleMethod = paint.getCycleMethod().ordinal();
    float[] fractions = paint.getFractions();
    Color[] colors = paint.getColors();
    int numStops = colors.length;
    int[] pixels = convertToIntArgbPrePixels(colors, linear);
    Point2D center = paint.getCenterPoint();
    Point2D focus = paint.getFocusPoint();
    float radius = paint.getRadius();

    // save original (untransformed) center and focus points
    double cx = center.getX();
    double cy = center.getY();
    double fx = focus.getX();
    double fy = focus.getY();

    // transform from gradient coords to device coords
    AffineTransform at = paint.getTransform();
    at.preConcatenate(sg2d.transform);
    focus = at.transform(focus, focus);

    // transform unit circle to gradient coords; we start with the
    // unit circle (center=(0,0), focus on positive x-axis, radius=1)
    // and then transform into gradient space
    at.translate(cx, cy);
    at.rotate(fx - cx, fy - cy);
    at.scale(radius, radius);

    // invert to get mapping from device coords to unit circle
    try {
        at.invert();
    } catch (Exception e) {
        at.setToScale(0.0, 0.0);
    }
    focus = at.transform(focus, focus);

    // clamp the focus point so that it does not rest on, or outside
    // of, the circumference of the gradient circle
    fx = Math.min(focus.getX(), 0.99);

    // assert rq.lock.isHeldByCurrentThread();
    rq.ensureCapacity(20 + 28 + (numStops*4*2));
    RenderBuffer buf = rq.getBuffer();
    buf.putInt(SET_RADIAL_GRADIENT_PAINT);
    buf.putInt(useMask ? 1 : 0);
    buf.putInt(linear  ? 1 : 0);
    buf.putInt(numStops);
    buf.putInt(cycleMethod);
    buf.putFloat((float)at.getScaleX());
    buf.putFloat((float)at.getShearX());
    buf.putFloat((float)at.getTranslateX());
    buf.putFloat((float)at.getShearY());
    buf.putFloat((float)at.getScaleY());
    buf.putFloat((float)at.getTranslateY());
    buf.putFloat((float)fx);
    buf.put(fractions);
    buf.put(pixels);
}
 
Example 16
/**
 * We use OpenGL's texture coordinate generator to automatically
 * map the TexturePaint image to the geometry being rendered.  The
 * generator uses two separate plane equations that take the (x,y)
 * location (in device space) of the fragment being rendered to
 * calculate (u,v) texture coordinates for that fragment:
 *     u = Ax + By + Cz + Dw
 *     v = Ex + Fy + Gz + Hw
 *
 * Since we use a 2D orthographic projection, we can assume that z=0
 * and w=1 for any fragment.  So we need to calculate appropriate
 * values for the plane equation constants (A,B,D) and (E,F,H) such
 * that {u,v}=0 for the top-left of the TexturePaint's anchor
 * rectangle and {u,v}=1 for the bottom-right of the anchor rectangle.
 * We can easily make the texture image repeat for {u,v} values
 * outside the range [0,1] by specifying the GL_REPEAT texture wrap
 * mode.
 *
 * Calculating the plane equation constants is surprisingly simple.
 * We can think of it as an inverse matrix operation that takes
 * device space coordinates and transforms them into user space
 * coordinates that correspond to a location relative to the anchor
 * rectangle.  First, we translate and scale the current user space
 * transform by applying the anchor rectangle bounds.  We then take
 * the inverse of this affine transform.  The rows of the resulting
 * inverse matrix correlate nicely to the plane equation constants
 * we were seeking.
 */
private static void setTexturePaint(RenderQueue rq,
                                    SunGraphics2D sg2d,
                                    TexturePaint paint,
                                    boolean useMask)
{
    BufferedImage bi = paint.getImage();
    SurfaceData dstData = sg2d.surfaceData;
    SurfaceData srcData =
        dstData.getSourceSurfaceData(bi, SunGraphics2D.TRANSFORM_ISIDENT,
                                     CompositeType.SrcOver, null);
    boolean filter =
        (sg2d.interpolationType !=
         AffineTransformOp.TYPE_NEAREST_NEIGHBOR);

    // calculate plane equation constants
    AffineTransform at = (AffineTransform)sg2d.transform.clone();
    Rectangle2D anchor = paint.getAnchorRect();
    at.translate(anchor.getX(), anchor.getY());
    at.scale(anchor.getWidth(), anchor.getHeight());

    double xp0, xp1, xp3, yp0, yp1, yp3;
    try {
        at.invert();
        xp0 = at.getScaleX();
        xp1 = at.getShearX();
        xp3 = at.getTranslateX();
        yp0 = at.getShearY();
        yp1 = at.getScaleY();
        yp3 = at.getTranslateY();
    } catch (java.awt.geom.NoninvertibleTransformException e) {
        xp0 = xp1 = xp3 = yp0 = yp1 = yp3 = 0.0;
    }

    // assert rq.lock.isHeldByCurrentThread();
    rq.ensureCapacityAndAlignment(68, 12);
    RenderBuffer buf = rq.getBuffer();
    buf.putInt(SET_TEXTURE_PAINT);
    buf.putInt(useMask ? 1 : 0);
    buf.putInt(filter ? 1 : 0);
    buf.putLong(srcData.getNativeOps());
    buf.putDouble(xp0).putDouble(xp1).putDouble(xp3);
    buf.putDouble(yp0).putDouble(yp1).putDouble(yp3);
}
 
Example 17
/**
 * We use OpenGL's texture coordinate generator to automatically
 * map the TexturePaint image to the geometry being rendered.  The
 * generator uses two separate plane equations that take the (x,y)
 * location (in device space) of the fragment being rendered to
 * calculate (u,v) texture coordinates for that fragment:
 *     u = Ax + By + Cz + Dw
 *     v = Ex + Fy + Gz + Hw
 *
 * Since we use a 2D orthographic projection, we can assume that z=0
 * and w=1 for any fragment.  So we need to calculate appropriate
 * values for the plane equation constants (A,B,D) and (E,F,H) such
 * that {u,v}=0 for the top-left of the TexturePaint's anchor
 * rectangle and {u,v}=1 for the bottom-right of the anchor rectangle.
 * We can easily make the texture image repeat for {u,v} values
 * outside the range [0,1] by specifying the GL_REPEAT texture wrap
 * mode.
 *
 * Calculating the plane equation constants is surprisingly simple.
 * We can think of it as an inverse matrix operation that takes
 * device space coordinates and transforms them into user space
 * coordinates that correspond to a location relative to the anchor
 * rectangle.  First, we translate and scale the current user space
 * transform by applying the anchor rectangle bounds.  We then take
 * the inverse of this affine transform.  The rows of the resulting
 * inverse matrix correlate nicely to the plane equation constants
 * we were seeking.
 */
private static void setTexturePaint(RenderQueue rq,
                                    SunGraphics2D sg2d,
                                    TexturePaint paint,
                                    boolean useMask)
{
    BufferedImage bi = paint.getImage();
    SurfaceData dstData = sg2d.surfaceData;
    SurfaceData srcData =
        dstData.getSourceSurfaceData(bi, SunGraphics2D.TRANSFORM_ISIDENT,
                                     CompositeType.SrcOver, null);
    boolean filter =
        (sg2d.interpolationType !=
         AffineTransformOp.TYPE_NEAREST_NEIGHBOR);

    // calculate plane equation constants
    AffineTransform at = (AffineTransform)sg2d.transform.clone();
    Rectangle2D anchor = paint.getAnchorRect();
    at.translate(anchor.getX(), anchor.getY());
    at.scale(anchor.getWidth(), anchor.getHeight());

    double xp0, xp1, xp3, yp0, yp1, yp3;
    try {
        at.invert();
        xp0 = at.getScaleX();
        xp1 = at.getShearX();
        xp3 = at.getTranslateX();
        yp0 = at.getShearY();
        yp1 = at.getScaleY();
        yp3 = at.getTranslateY();
    } catch (java.awt.geom.NoninvertibleTransformException e) {
        xp0 = xp1 = xp3 = yp0 = yp1 = yp3 = 0.0;
    }

    // assert rq.lock.isHeldByCurrentThread();
    rq.ensureCapacityAndAlignment(68, 12);
    RenderBuffer buf = rq.getBuffer();
    buf.putInt(SET_TEXTURE_PAINT);
    buf.putInt(useMask ? 1 : 0);
    buf.putInt(filter ? 1 : 0);
    buf.putLong(srcData.getNativeOps());
    buf.putDouble(xp0).putDouble(xp1).putDouble(xp3);
    buf.putDouble(yp0).putDouble(yp1).putDouble(yp3);
}
 
Example 18
Source Project: ghidra   File: MouseDebugPaintable.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void paint(Graphics g) {

	if (shapes.isEmpty()) {
		return;
	}

	Graphics2D g2d = (Graphics2D) g;
	AffineTransform oldXform = g2d.getTransform();

	RenderContext<?, ?> rc = viewer.getRenderContext();
	MultiLayerTransformer multiLayerTransformer = rc.getMultiLayerTransformer();
	MutableTransformer layoutXformer = multiLayerTransformer.getTransformer(Layer.LAYOUT);
	AffineTransform layoutXform = layoutXformer.getTransform();

	double tx = layoutXform.getTranslateX();
	double ty = layoutXform.getTranslateY();

	for (PaintableShape s : shapes) {

		if (s.isShapeFinished()) {
			// this will draw the shape, after dragging is finished, at a position
			// relative to its start point 
			double dx = tx - s.getTx();
			double dy = ty - s.getTy();

			AffineTransform newXform = new AffineTransform(oldXform);
			newXform.translate(dx, dy);
			g2d.setTransform(newXform);
		}

		Stroke oldStroke = g2d.getStroke();
		Color oldColor = g2d.getColor();

		s.paint(g2d);

		g2d.setStroke(oldStroke);
		g2d.setColor(oldColor);
		g2d.setTransform(oldXform);
	}
}
 
Example 19
Source Project: gcs   File: LayerUtility.java    License: Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Imports a page from some PDF file as a Form XObject so it can be placed on another page
 * in the target document.
 * <p>
 * You may want to call {@link #wrapInSaveRestore(PDPage) wrapInSaveRestore(PDPage)} before invoking the Form XObject to
 * make sure that the graphics state is reset.
 * 
 * @param sourceDoc the source PDF document that contains the page to be copied
 * @param page the page in the source PDF document to be copied
 * @return a Form XObject containing the original page's content
 * @throws IOException if an I/O error occurs
 */
public PDFormXObject importPageAsForm(PDDocument sourceDoc, PDPage page) throws IOException
{
    importOcProperties(sourceDoc);

    PDStream newStream = new PDStream(targetDoc, page.getContents(), COSName.FLATE_DECODE);
    PDFormXObject form = new PDFormXObject(newStream);

    //Copy resources
    PDResources pageRes = page.getResources();
    PDResources formRes = new PDResources();
    cloner.cloneMerge(pageRes, formRes);
    form.setResources(formRes);

    //Transfer some values from page to form
    transferDict(page.getCOSObject(), form.getCOSObject(), PAGE_TO_FORM_FILTER, true);

    Matrix matrix = form.getMatrix();
    AffineTransform at = matrix.createAffineTransform();
    PDRectangle mediaBox = page.getMediaBox();
    PDRectangle cropBox = page.getCropBox();
    PDRectangle viewBox = (cropBox != null ? cropBox : mediaBox);

    //Handle the /Rotation entry on the page dict
    int rotation = page.getRotation();

    //Transform to FOP's user space
    //at.scale(1 / viewBox.getWidth(), 1 / viewBox.getHeight());
    at.translate(mediaBox.getLowerLeftX() - viewBox.getLowerLeftX(),
            mediaBox.getLowerLeftY() - viewBox.getLowerLeftY());
    switch (rotation)
    {
    case 90:
        at.scale(viewBox.getWidth() / viewBox.getHeight(), viewBox.getHeight() / viewBox.getWidth());
        at.translate(0, viewBox.getWidth());
        at.rotate(-Math.PI / 2.0);
        break;
    case 180:
        at.translate(viewBox.getWidth(), viewBox.getHeight());
        at.rotate(-Math.PI);
        break;
    case 270:
        at.scale(viewBox.getWidth() / viewBox.getHeight(), viewBox.getHeight() / viewBox.getWidth());
        at.translate(viewBox.getHeight(), 0);
        at.rotate(-Math.PI * 1.5);
        break;
    default:
        //no additional transformations necessary
    }
    //Compensate for Crop Boxes not starting at 0,0
    at.translate(-viewBox.getLowerLeftX(), -viewBox.getLowerLeftY());
    if (!at.isIdentity())
    {
        form.setMatrix(at);
    }

    BoundingBox bbox = new BoundingBox();
    bbox.setLowerLeftX(viewBox.getLowerLeftX());
    bbox.setLowerLeftY(viewBox.getLowerLeftY());
    bbox.setUpperRightX(viewBox.getUpperRightX());
    bbox.setUpperRightY(viewBox.getUpperRightY());
    form.setBBox(new PDRectangle(bbox));

    return form;
}
 
Example 20
/**
 * This method calculates six m** values and a focusX value that
 * are used by the native fragment shader.  These techniques are
 * based on a whitepaper by Daniel Rice on radial gradient performance
 * (attached to the bug report for 6521533).  One can refer to that
 * document for the complete set of formulas and calculations, but
 * the basic goal is to compose a transform that will convert an
 * (x,y) position in device space into a "u" value that represents
 * the relative distance to the gradient focus point.  The resulting
 * value can be used to look up the appropriate color by linearly
 * interpolating between the two nearest colors in the gradient.
 */
private static void setRadialGradientPaint(RenderQueue rq,
                                           SunGraphics2D sg2d,
                                           RadialGradientPaint paint,
                                           boolean useMask)
{
    boolean linear =
        (paint.getColorSpace() == ColorSpaceType.LINEAR_RGB);
    int cycleMethod = paint.getCycleMethod().ordinal();
    float[] fractions = paint.getFractions();
    Color[] colors = paint.getColors();
    int numStops = colors.length;
    int[] pixels = convertToIntArgbPrePixels(colors, linear);
    Point2D center = paint.getCenterPoint();
    Point2D focus = paint.getFocusPoint();
    float radius = paint.getRadius();

    // save original (untransformed) center and focus points
    double cx = center.getX();
    double cy = center.getY();
    double fx = focus.getX();
    double fy = focus.getY();

    // transform from gradient coords to device coords
    AffineTransform at = paint.getTransform();
    at.preConcatenate(sg2d.transform);
    focus = at.transform(focus, focus);

    // transform unit circle to gradient coords; we start with the
    // unit circle (center=(0,0), focus on positive x-axis, radius=1)
    // and then transform into gradient space
    at.translate(cx, cy);
    at.rotate(fx - cx, fy - cy);
    at.scale(radius, radius);

    // invert to get mapping from device coords to unit circle
    try {
        at.invert();
    } catch (Exception e) {
        at.setToScale(0.0, 0.0);
    }
    focus = at.transform(focus, focus);

    // clamp the focus point so that it does not rest on, or outside
    // of, the circumference of the gradient circle
    fx = Math.min(focus.getX(), 0.99);

    // assert rq.lock.isHeldByCurrentThread();
    rq.ensureCapacity(20 + 28 + (numStops*4*2));
    RenderBuffer buf = rq.getBuffer();
    buf.putInt(SET_RADIAL_GRADIENT_PAINT);
    buf.putInt(useMask ? 1 : 0);
    buf.putInt(linear  ? 1 : 0);
    buf.putInt(numStops);
    buf.putInt(cycleMethod);
    buf.putFloat((float)at.getScaleX());
    buf.putFloat((float)at.getShearX());
    buf.putFloat((float)at.getTranslateX());
    buf.putFloat((float)at.getShearY());
    buf.putFloat((float)at.getScaleY());
    buf.putFloat((float)at.getTranslateY());
    buf.putFloat((float)fx);
    buf.put(fractions);
    buf.put(pixels);
}