Java Code Examples for java.awt.geom.AffineTransform

The following examples show how to use java.awt.geom.AffineTransform. These examples are extracted from open source projects.
Example 1
Project: jdk8u-dev-jdk   File: DrawRotatedStringUsingRotatedFont.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates an BufferedImage and draws a text, using two transformations,
 * one for graphics and one for font.
 */
private static BufferedImage createImage(final boolean aa,
                                         final AffineTransform gtx,
                                         final AffineTransform ftx) {
    final BufferedImage bi = new BufferedImage(SIZE, SIZE, TYPE_INT_RGB);
    final Graphics2D bg = bi.createGraphics();
    bg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        aa ? RenderingHints.VALUE_ANTIALIAS_ON
                           : RenderingHints.VALUE_ANTIALIAS_OFF);
    bg.setColor(Color.RED);
    bg.fillRect(0, 0, SIZE, SIZE);
    bg.translate(100, 100);
    bg.transform(gtx);
    bg.setColor(Color.BLACK);
    bg.setFont(bg.getFont().deriveFont(20.0f).deriveFont(ftx));
    bg.drawString(STR, 0, 0);
    bg.dispose();
    return bi;
}
 
Example 2
Project: openjdk-jdk8u   File: Font2D.java    License: GNU General Public License v2.0 6 votes vote down vote up
public float getItalicAngle(Font font, AffineTransform at,
                            Object aaHint, Object fmHint) {
    /* hardwire psz=12 as that's typical and AA vs non-AA for 'gasp' mode
     * isn't important for the caret slope of this rarely used API.
     */
    int aa = FontStrikeDesc.getAAHintIntVal(aaHint, this, 12);
    int fm = FontStrikeDesc.getFMHintIntVal(fmHint);
    FontStrike strike = getStrike(font, at, aa, fm);
    StrikeMetrics metrics = strike.getFontMetrics();
    if (metrics.ascentY == 0 || metrics.ascentX == 0) {
        return 0f;
    } else {
        /* ascent is "up" from the baseline so its typically
         * a negative value, so we need to compensate
         */
        return metrics.ascentX/-metrics.ascentY;
    }
}
 
Example 3
Project: workcraft   File: TouchableTransformerTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testTranslateHitTest() {
    TouchableTransformer toucher = new TouchableTransformer(
            new Dummy() {
                @Override
                public boolean hitTest(Point2D point) {
                    return point.distanceSq(0, 0) < 1.0;
                }
            }, AffineTransform.getTranslateInstance(10, 1));

    Assertions.assertTrue(toucher.hitTest(new Point2D.Double(10, 1)));
    Assertions.assertTrue(toucher.hitTest(new Point2D.Double(10.9, 1)));
    Assertions.assertTrue(toucher.hitTest(new Point2D.Double(9.1, 1)));
    Assertions.assertFalse(toucher.hitTest(new Point2D.Double(11.1, 1)));
    Assertions.assertFalse(toucher.hitTest(new Point2D.Double(8.9, 1)));
    Assertions.assertTrue(toucher.hitTest(new Point2D.Double(10.6, 1.6)));
    Assertions.assertFalse(toucher.hitTest(new Point2D.Double(10.8, 1.8)));
    Assertions.assertTrue(toucher.hitTest(new Point2D.Double(9.4, 0.4)));
    Assertions.assertFalse(toucher.hitTest(new Point2D.Double(9.2, 0.2)));
}
 
Example 4
Project: coming   File: NPEfix_00174_t.java    License: MIT License 6 votes vote down vote up
/** Build an affine line transform from a n {@code AffineTransform}.
 * @param transform transform to use (must be invertible otherwise
 * the {@link LineTransform#apply(Hyperplane)} method would work
 * only for some lines, and fail for other ones)
 * @exception MathIllegalArgumentException if the transform is non invertible
 */
public LineTransform(final AffineTransform transform) throws MathIllegalArgumentException {

    final double[] m = new double[6];
    transform.getMatrix(m);
    cXX = m[0];
    cXY = m[2];
    cX1 = m[4];
    cYX = m[1];
    cYY = m[3];
    cY1 = m[5];

    c1Y = cXY * cY1 - cYY * cX1;
    c1X = cXX * cY1 - cYX * cX1;
    c11 = cXX * cYY - cYX * cXY;

    if (FastMath.abs(c11) < 1.0e-20) {
        throw new MathIllegalArgumentException(LocalizedFormats.NON_INVERTIBLE_TRANSFORM);
    }

}
 
Example 5
Project: rapidminer-studio   File: SurfacePlot3D.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public JComponent getPlotter() {
	DataTable table = getDataTable();
	if (table != null && table.getNumberOfRows() > MAX_NUMBER_OF_ROWS) {
		LogService.getRoot().log(Level.INFO, "com.rapidminer.gui.plotter.mathplot.SurfacePlot2D.too_many_examples",
				new Object[] { table.getNumberOfRows(), MAX_NUMBER_OF_ROWS });
		// Display Label with error message because Plot3DPanel can not handle such a lot of
		// data points
		JLabel label = new JLabel(I18N.getGUILabel("surface3DPlot.too_many_examples", MAX_NUMBER_OF_ROWS));
		label.setHorizontalAlignment(SwingConstants.CENTER);
		Font originalFont = label.getFont();
		label.setFont(originalFont.deriveFont((float) (originalFont.getSize() * 1.25)));
		originalFont.deriveFont(new AffineTransform());

		return label;
	} else {
		return super.getPlotter();
	}
}
 
Example 6
Project: jdk8u-dev-jdk   File: TransformingPathConsumer2D.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static PathConsumer2D
    deltaTransformConsumer(PathConsumer2D out,
                           AffineTransform at)
{
    if (at == null) {
        return out;
    }
    float Mxx = (float) at.getScaleX();
    float Mxy = (float) at.getShearX();
    float Myx = (float) at.getShearY();
    float Myy = (float) at.getScaleY();
    if (Mxy == 0f && Myx == 0f) {
        if (Mxx == 1f && Myy == 1f) {
            return out;
        } else {
            return new DeltaScaleFilter(out, Mxx, Myy);
        }
    } else {
        return new DeltaTransformFilter(out, Mxx, Mxy, Myx, Myy);
    }
}
 
Example 7
Project: openjdk-jdk9   File: PathGraphics.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Draws the outline of the specified rectangle.
 * The left and right edges of the rectangle are at
 * {@code x} and <code>x&nbsp;+&nbsp;width</code>.
 * The top and bottom edges are at
 * {@code y} and <code>y&nbsp;+&nbsp;height</code>.
 * The rectangle is drawn using the graphics context's current color.
 * @param         x   the <i>x</i> coordinate
 *                         of the rectangle to be drawn.
 * @param         y   the <i>y</i> coordinate
 *                         of the rectangle to be drawn.
 * @param         width   the width of the rectangle to be drawn.
 * @param         height   the height of the rectangle to be drawn.
 * @see          java.awt.Graphics#fillRect
 * @see          java.awt.Graphics#clearRect
 */
public void drawRect(int x, int y, int width, int height) {

    Paint paint = getPaint();

    try {
        AffineTransform deviceTransform = getTransform();
        if (getClip() != null) {
            deviceClip(getClip().getPathIterator(deviceTransform));
        }

        deviceFrameRect(x, y, width, height, (Color) paint);

    } catch (ClassCastException e) {
        throw new IllegalArgumentException("Expected a Color instance");
    }

}
 
Example 8
Project: jdk8u-jdk   File: GraphicComponent.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a new GraphicComponent.  start and limit are indices
 * into charLtoV and levels.  charsLtoV and levels may be adopted.
 */
public GraphicComponent(GraphicAttribute graphic,
                        Decoration decorator,
                        int[] charsLtoV,
                        byte[] levels,
                        int start,
                        int limit,
                        AffineTransform baseTx) {

    if (limit <= start) {
        throw new IllegalArgumentException("0 or negative length in GraphicComponent");
    }
    this.graphic = graphic;
    this.graphicAdvance = graphic.getAdvance();
    this.decorator = decorator;
    this.cm = createCoreMetrics(graphic);
    this.baseTx = baseTx;

    initLocalOrdering(charsLtoV, levels, start, limit);
}
 
Example 9
Project: jdk8u-jdk   File: StandardGlyphVector.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void setGlyphTransform(int ix, AffineTransform newTX) {
    if (ix < 0 || ix >= glyphs.length) {
        throw new IndexOutOfBoundsException("ix = " + ix);
    }

    if (gti == null) {
        if (newTX == null || newTX.isIdentity()) {
            return;
        }
        gti = new GlyphTransformInfo(this);
    }
    gti.setGlyphTransform(ix, newTX); // sets flags
    if (gti.transformCount() == 0) {
        gti = null;
    }
}
 
Example 10
Project: jdk8u-jdk   File: AttributeValues.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static AffineTransform extractRotation(Point2D.Double pt,
    AffineTransform tx, boolean andTranslation) {

    tx.deltaTransform(pt, pt);
    AffineTransform rtx = AffineTransform.getRotateInstance(pt.x, pt.y);

    try {
        AffineTransform rtxi = rtx.createInverse();
        double dx = tx.getTranslateX();
        double dy = tx.getTranslateY();
        tx.preConcatenate(rtxi);
        if (andTranslation) {
            if (dx != 0 || dy != 0) {
                tx.setTransform(tx.getScaleX(), tx.getShearY(),
                                tx.getShearX(), tx.getScaleY(), 0, 0);
                rtx.setTransform(rtx.getScaleX(), rtx.getShearY(),
                                 rtx.getShearX(), rtx.getScaleY(), dx, dy);
            }
        }
    }
    catch (NoninvertibleTransformException e) {
        return null;
    }
    return rtx;
}
 
Example 11
Project: nordpos   File: PrintItemBarcode.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void draw(Graphics2D g, int x, int y, int width) {
    Graphics2D g2d = (Graphics2D) g;
    AffineTransform oldt = g2d.getTransform();
    g2d.translate(x - 10 + (width - (int) (m_iWidth * scale)) / 2, y + 10);
    g2d.scale(scale, scale);

    try {
        if (m_qrMatrix != null) {
            com.google.zxing.Writer writer = new QRCodeWriter();
            m_qrMatrix = writer.encode(m_sCode, com.google.zxing.BarcodeFormat.QR_CODE, m_iWidth, m_iHeight);
            g2d.drawImage(MatrixToImageWriter.toBufferedImage(m_qrMatrix), null, 0, 0);
        } else if (m_barcode != null) {
            m_barcode.generateBarcode(new Java2DCanvasProvider(g2d, 0), m_sCode);
        }
    } catch (IllegalArgumentException | WriterException ex) {
        g2d.drawRect(0, 0, m_iWidth, m_iHeight);
        g2d.drawLine(0, 0, m_iWidth, m_iHeight);
        g2d.drawLine(m_iWidth, 0, 0, m_iHeight);
    }

    g2d.setTransform(oldt);
}
 
Example 12
Project: jdk8u-jdk   File: SynthPainterImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Paints the border 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 paintTextFieldBorder(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 13
Project: openjdk-jdk8u-backup   File: SunGraphics2D.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the Transform in the current graphics state.
 * @param Tx The Transform object to be used in the rendering process.
 * @see #transform
 * @see TransformChain
 * @see AffineTransform
 */
@Override
public void setTransform(AffineTransform Tx) {
    if ((constrainX | constrainY) == 0 && devScale == 1) {
        transform.setTransform(Tx);
    } else {
        transform.setTransform(devScale, 0, 0, devScale, constrainX,
                               constrainY);
        transform.concatenate(Tx);
    }
    invalidateTransform();
}
 
Example 14
Project: jdk8u-jdk   File: TextMeasureTests.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    GVContext gvctx = (GVContext)ctx;
    GlyphVector gv = gvctx.gv;
    AffineTransform tx;
    do {
        for (int i = 0, e = gv.getNumGlyphs(); i < e; ++i) {
            tx = gv.getGlyphTransform(i);
        }
    } while (--numReps >= 0);
}
 
Example 15
Project: dragonwell8_jdk   File: AffineTransformOp.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs an <CODE>AffineTransformOp</CODE> given an affine transform
 * and the interpolation type.
 *
 * @param xform The <CODE>AffineTransform</CODE> to use for the operation.
 * @param interpolationType One of the integer
 * interpolation type constants defined by this class:
 * {@link #TYPE_NEAREST_NEIGHBOR TYPE_NEAREST_NEIGHBOR},
 * {@link #TYPE_BILINEAR TYPE_BILINEAR},
 * {@link #TYPE_BICUBIC TYPE_BICUBIC}.
 * @throws ImagingOpException if the transform is non-invertible.
 */
public AffineTransformOp(AffineTransform xform, int interpolationType) {
    validateTransform(xform);
    this.xform = (AffineTransform)xform.clone();
    switch(interpolationType) {
        case TYPE_NEAREST_NEIGHBOR:
        case TYPE_BILINEAR:
        case TYPE_BICUBIC:
            break;
    default:
        throw new IllegalArgumentException("Unknown interpolation type: "+
                                           interpolationType);
    }
    this.interpolationType = interpolationType;
}
 
Example 16
Project: openjdk-8   File: SynthPainterImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void paintBackground(SynthContext ctx, Graphics g, int x, int y,
                             int w, int h, AffineTransform transform) {
    // if the background color of the component is 100% transparent
    // then we should not paint any background graphics. This is a solution
    // for there being no way of turning off Nimbus background painting as
    // basic components are all non-opaque by default.
    Component c = ctx.getComponent();
    Color bg = (c != null) ? c.getBackground() : null;
    if (bg == null || bg.getAlpha() > 0){
        Painter backgroundPainter = style.getBackgroundPainter(ctx);
        if (backgroundPainter != null) {
            paint(backgroundPainter, ctx, g, x, y, w, h,transform);
        }
    }
}
 
Example 17
Project: Pixelitor   File: CloneBrush.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Recalculates the brush stamp image before each dab
 */
@Override
void setupBrushStamp(PPoint p) {
    Graphics2D g = brushImage.createGraphics();

    type.beforeDrawImage(g);

    // the current sampling coordinates relative to the source image
    double currSrcX = dx - p.getImX();
    double currSrcY = dy - p.getImY();

    // Now calculate the transformation from the source to the brush image.
    // Concatenated transformations have a last-specified-first-applied
    // order, so start with the last transformation
    // that works when there is no scaling/rotating
    var transform = AffineTransform.getTranslateInstance(
            currSrcX + radius, currSrcY + radius);

    if (scaleX != 1.0 || scaleY != 1.0 || rotate != 0.0) {
        g.setRenderingHint(KEY_INTERPOLATION, VALUE_INTERPOLATION_BILINEAR);
        // we need to scale/rotate the image
        // around the source point, so translate first
        transform.translate(origSrcX, origSrcY);
        transform.scale(scaleX, scaleY);
        transform.rotate(rotate);
        transform.translate(-origSrcX, -origSrcY);
    }

    g.drawImage(sourceImage, transform, null);
    type.afterDrawImage(g);

    g.dispose();

    debugImage();
}
 
Example 18
Project: netcdf-java   File: ScaledPanel.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * map world coords to screen coords.
 *
 * @param world world coordinate rectangle
 * @param screen screen coordinate rectangle
 * @return AffineTransform for converting world to screen.
 */
private AffineTransform calcTransform(Rectangle2D screen, Bounds world) {
  // scale to limiting dimension
  double xs = screen.getWidth() / (world.getRight() - world.getLeft());
  double ys = screen.getHeight() / (world.getLower() - world.getUpper());

  AffineTransform cat = new AffineTransform();
  cat.setToScale(xs, ys);
  cat.translate(-world.getLeft(), -world.getUpper());

  if (debugTransform) {
    System.out.println("TPanel calcTransform = ");
    System.out.println("  screen = " + screen);
    System.out.println("  world = " + world);

    System.out.println("  transform = " + cat.getScaleX() + " " + cat.getShearX() + " " + cat.getTranslateX());
    System.out.println("              " + cat.getShearY() + " " + cat.getScaleY() + " " + cat.getTranslateY());

    Point2D src = new Point2D.Double(world.getLeft(), world.getUpper());
    Point2D dst = new Point2D.Double(0.0, 0.0);

    System.out.println("  upper left pt = " + src);
    System.out.println("  transform = " + cat.transform(src, dst));

    src = new Point2D.Double(world.getRight(), world.getLower());
    System.out.println("  lower right pt = " + src);
    System.out.println("  transform = " + cat.transform(src, dst));
  }
  return cat;
}
 
Example 19
Project: gama   File: SVGElement.java    License: GNU General Public License v3.0 5 votes vote down vote up
static protected AffineTransform parseTransform(final String val) throws SVGException {
	final Matcher matchExpression = Pattern.compile("\\w+\\([^)]*\\)").matcher("");

	final AffineTransform retXform = new AffineTransform();

	matchExpression.reset(val);
	while (matchExpression.find()) {
		retXform.concatenate(parseSingleTransform(matchExpression.group()));
	}

	return retXform;
}
 
Example 20
Project: openjdk-jdk8u   File: DrawImage.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void transformImage(SunGraphics2D sg, Image img,
                              AffineTransform tx, int interpType,
                              int sx1, int sy1, int sx2, int sy2,
                              Color bgColor)
{
    // Transform 3 source corners by tx and analyze them
    // for simplified operations (Copy or Scale).  Using
    // 3 points lets us analyze any kind of transform,
    // even transforms that involve very tiny amounts of
    // rotation or skew to see if they degenerate to a
    // simple scale or copy operation within the allowable
    // error bounds.
    // Note that we use (0,0,w,h) instead of (sx1,sy1,sx2,sy2)
    // because the transform is already translated such that
    // the origin is where sx1, sy1 should go.
    double coords[] = new double[6];
    /* index:  0  1    2  3    4  5  */
    /* coord: (0, 0), (w, h), (0, h) */
    coords[2] = sx2 - sx1;
    coords[3] = coords[5] = sy2 - sy1;
    tx.transform(coords, 0, coords, 0, 3);
    // First test if the X coords of the transformed UL
    // and LL points match and that the Y coords of the
    // transformed LR and LL points also match.
    // If they do then it is a "rectilinear" transform and
    // tryCopyOrScale will make sure it is upright and
    // integer-based.
    if (Math.abs(coords[0] - coords[4]) < MAX_TX_ERROR &&
        Math.abs(coords[3] - coords[5]) < MAX_TX_ERROR &&
        tryCopyOrScale(sg, img, sx1, sy1, sx2, sy2,
                       bgColor, interpType, coords))
    {
        return;
    }

    renderImageXform(sg, img, tx, interpType, sx1, sy1, sx2, sy2, bgColor);
}
 
Example 21
Project: birt   File: SwingGraphicsUtil.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private static BufferedImage renderRotatedObject( Object src, double angle,
		int width, int height, double tx, double ty )
{
	BufferedImage dest = new BufferedImage( width,
			height,
			BufferedImage.TYPE_INT_ARGB );

	Graphics2D g2d = (Graphics2D) dest.getGraphics( );
	g2d.setColor( Color.black );
	g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING,
			RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
	g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING,
			RenderingHints.VALUE_ANTIALIAS_ON );

	AffineTransform at = AffineTransform.getRotateInstance( angle );
	at.translate( tx, ty );
	g2d.setTransform( at );

	if ( src instanceof TextLayout )
	{
		TextLayout tl = (TextLayout) src;
		tl.draw( g2d, 0, tl.getAscent( ) );
	}
	else if ( src instanceof Image )
	{
		g2d.drawImage( (Image) src, 0, 0, null );
	}
	g2d.dispose( );

	return dest;
}
 
Example 22
Project: openjdk-8-source   File: TexturePaintContext.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static PaintContext getContext(BufferedImage bufImg,
                                      AffineTransform xform,
                                      RenderingHints hints,
                                      Rectangle devBounds) {
    WritableRaster raster = bufImg.getRaster();
    ColorModel cm = bufImg.getColorModel();
    int maxw = devBounds.width;
    Object val = hints.get(RenderingHints.KEY_INTERPOLATION);
    boolean filter =
        (val == null
         ? (hints.get(RenderingHints.KEY_RENDERING) == RenderingHints.VALUE_RENDER_QUALITY)
         : (val != RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR));
    if (raster instanceof IntegerInterleavedRaster &&
        (!filter || isFilterableDCM(cm)))
    {
        IntegerInterleavedRaster iir = (IntegerInterleavedRaster) raster;
        if (iir.getNumDataElements() == 1 && iir.getPixelStride() == 1) {
            return new Int(iir, cm, xform, maxw, filter);
        }
    } else if (raster instanceof ByteInterleavedRaster) {
        ByteInterleavedRaster bir = (ByteInterleavedRaster) raster;
        if (bir.getNumDataElements() == 1 && bir.getPixelStride() == 1) {
            if (filter) {
                if (isFilterableICM(cm)) {
                    return new ByteFilter(bir, cm, xform, maxw);
                }
            } else {
                return new Byte(bir, cm, xform, maxw);
            }
        }
    }
    return new Any(raster, cm, xform, maxw, filter);
}
 
Example 23
Project: dragonwell8_jdk   File: TexturePaintContext.java    License: GNU General Public License v2.0 5 votes vote down vote up
public Byte(ByteInterleavedRaster srcRas, ColorModel cm,
            AffineTransform xform, int maxw)
{
    super(cm, xform, srcRas.getWidth(), srcRas.getHeight(), maxw);
    this.srcRas = srcRas;
    this.inData = srcRas.getDataStorage();
    this.inSpan = srcRas.getScanlineStride();
    this.inOff = srcRas.getDataOffset(0);
}
 
Example 24
Project: jdk8u-jdk   File: GraphicsTests.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void init(Graphics2D g2d, Context ctx, Dimension dim) {
    int w = dim.width;
    int h = dim.height;
    AffineTransform at = new AffineTransform();
    at.translate(1.5, 1.5);
    g2d.transform(at);
    dim.setSize(w-3, h-3);
}
 
Example 25
Project: jdk8u-jdk   File: TextSourceLabel.java    License: GNU General Public License v2.0 5 votes vote down vote up
public AffineTransform getBaselineTransform() {
    Font font = source.getFont();
    if (font.hasLayoutAttributes()) {
        return AttributeValues.getBaselineTransform(font.getAttributes());
    }
    return null;
}
 
Example 26
Project: Java8CN   File: BasicProgressBarUI.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Paints the progress string.
 *
 * @param g Graphics used for drawing.
 * @param x x location of bounding box
 * @param y y location of bounding box
 * @param width width of bounding box
 * @param height height of bounding box
 * @param fillStart start location, in x or y depending on orientation,
 *        of the filled portion of the progress bar.
 * @param amountFull size of the fill region, either width or height
 *        depending upon orientation.
 * @param b Insets of the progress bar.
 */
private void paintString(Graphics g, int x, int y, int width, int height,
                         int fillStart, int amountFull, Insets b) {
    if (!(g instanceof Graphics2D)) {
        return;
    }

    Graphics2D g2 = (Graphics2D)g;
    String progressString = progressBar.getString();
    g2.setFont(progressBar.getFont());
    Point renderLocation = getStringPlacement(g2, progressString,
                                              x, y, width, height);
    Rectangle oldClip = g2.getClipBounds();

    if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) {
        g2.setColor(getSelectionBackground());
        SwingUtilities2.drawString(progressBar, g2, progressString,
                                   renderLocation.x, renderLocation.y);
        g2.setColor(getSelectionForeground());
        g2.clipRect(fillStart, y, amountFull, height);
        SwingUtilities2.drawString(progressBar, g2, progressString,
                                   renderLocation.x, renderLocation.y);
    } else { // VERTICAL
        g2.setColor(getSelectionBackground());
        AffineTransform rotate =
                AffineTransform.getRotateInstance(Math.PI/2);
        g2.setFont(progressBar.getFont().deriveFont(rotate));
        renderLocation = getStringPlacement(g2, progressString,
                                              x, y, width, height);
        SwingUtilities2.drawString(progressBar, g2, progressString,
                                   renderLocation.x, renderLocation.y);
        g2.setColor(getSelectionForeground());
        g2.clipRect(x, fillStart, width, amountFull);
        SwingUtilities2.drawString(progressBar, g2, progressString,
                                   renderLocation.x, renderLocation.y);
    }
    g2.setClip(oldClip);
}
 
Example 27
Project: TencentKona-8   File: GlyphRotationTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    font = new Font(fontName, Font.PLAIN, 15);
    if (!font.getFamily(java.util.Locale.ENGLISH).equals(fontName)) {
        return;
    }
    BufferedImage bi = new BufferedImage(SZ,SZ,BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bi.createGraphics();
    g2d.setColor(Color.white);
    g2d.fillRect(0, 0, SZ, SZ);
    g2d.setColor(Color.black);
    g2d.setFont(font);
    g2d.drawString("1", SZ/2, SZ/2);
    int pixCnt1 = countPixels(bi);
    AffineTransform at = AffineTransform.getRotateInstance(Math.PI/2);
    font = font.deriveFont(Font.PLAIN, at);
    g2d.setFont(font);
    g2d.drawString("1", SZ/2, SZ/2);
    int pixCnt2 = countPixels(bi);
    if (args.length > 0) {
        try {
           ImageIO.write(bi, "png", new java.io.File("im.png"));
        }  catch (Exception e) {}
    }
    if (pixCnt1 == pixCnt2) {
        String msg = "cnt 1 = " + pixCnt1 + " cnt 2 = " + pixCnt2;
        throw new RuntimeException(msg);
    }
}
 
Example 28
Project: lams   File: DrawShape.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static Rectangle2D getAnchor(Graphics2D graphics, Rectangle2D anchor) {
    if(graphics == null)  {
        return anchor;
    }

    AffineTransform tx = (AffineTransform)graphics.getRenderingHint(Drawable.GROUP_TRANSFORM);
    if(tx != null && !tx.isIdentity()) {
        anchor = tx.createTransformedShape(anchor).getBounds2D();
    }
    return anchor;
}
 
Example 29
Project: openjdk-8   File: DrawImage.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void transformImage(SunGraphics2D sg, Image img,
                              AffineTransform tx, int interpType,
                              int sx1, int sy1, int sx2, int sy2,
                              Color bgColor)
{
    // Transform 3 source corners by tx and analyze them
    // for simplified operations (Copy or Scale).  Using
    // 3 points lets us analyze any kind of transform,
    // even transforms that involve very tiny amounts of
    // rotation or skew to see if they degenerate to a
    // simple scale or copy operation within the allowable
    // error bounds.
    // Note that we use (0,0,w,h) instead of (sx1,sy1,sx2,sy2)
    // because the transform is already translated such that
    // the origin is where sx1, sy1 should go.
    double coords[] = new double[6];
    /* index:  0  1    2  3    4  5  */
    /* coord: (0, 0), (w, h), (0, h) */
    coords[2] = sx2 - sx1;
    coords[3] = coords[5] = sy2 - sy1;
    tx.transform(coords, 0, coords, 0, 3);
    // First test if the X coords of the transformed UL
    // and LL points match and that the Y coords of the
    // transformed LR and LL points also match.
    // If they do then it is a "rectilinear" transform and
    // tryCopyOrScale will make sure it is upright and
    // integer-based.
    if (Math.abs(coords[0] - coords[4]) < MAX_TX_ERROR &&
        Math.abs(coords[3] - coords[5]) < MAX_TX_ERROR &&
        tryCopyOrScale(sg, img, sx1, sy1, sx2, sy2,
                       bgColor, interpType, coords))
    {
        return;
    }

    renderImageXform(sg, img, tx, interpType, sx1, sy1, sx2, sy2, bgColor);
}
 
Example 30
Project: osp   File: BoundedImage.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Draws the bounds around the image.
 *
 * @param panel the drawing panel
 * @param g  the graphics context
 */
private void drawFixedBounds(DrawingPanel panel, Graphics g) {
  Point2D pt = new Point2D.Double(x, y);
  pt = toPixels.transform(pt, pt);
  Shape temp = new Rectangle2D.Double(pt.getX()-width/2, pt.getY()-height/2, width, height);
  computeFixedHotSpots(temp.getBounds2D());
  pixelBounds = temp.getBounds2D();
  if(theta!=0) {
    pixelBounds = AffineTransform.getRotateInstance(-theta, pt.getX(), pt.getY()).createTransformedShape(pixelBounds);
  }
  if(!selected) {
    return;
  }
  Graphics2D g2 = ((Graphics2D) g);
  g2.setPaint(boundsColor);
  g2.draw(pixelBounds);
  if(xyDrag) {
    g2.fillRect((int) hotSpots[CENTER].getX()-delta, (int) hotSpots[CENTER].getY()-delta, d2, d2);
    g2.setColor(edgeColor);
    g2.fillOval((int) hotSpots[CENTER].getX()-1, (int) hotSpots[CENTER].getY()-1, 3, 3);
    g2.setPaint(boundsColor);
  }
  if(rotateDrag) {
    g2.fillOval((int) hotSpots[CORNER].getX()-delta, (int) hotSpots[CORNER].getY()-delta, d2, d2);
  }
  if(heightDrag) {
    g2.fillRect((int) hotSpots[TOP].getX()-delta, (int) hotSpots[TOP].getY()-delta, d2, d2);
    g2.fillRect((int) hotSpots[BOTTOM].getX()-delta, (int) hotSpots[BOTTOM].getY()-delta, d2, d2);
  }
  if(widthDrag) {
    g2.fillRect((int) hotSpots[LEFT].getX()-delta, (int) hotSpots[LEFT].getY()-delta, d2, d2);
    g2.fillRect((int) hotSpots[RIGHT].getX()-delta, (int) hotSpots[RIGHT].getY()-delta, d2, d2);
  }
  g.setColor(Color.BLACK);
}
 
Example 31
Project: Briss-2.0   File: ClusterImageData.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static BufferedImage scaleImage(final BufferedImage bsrc, final int width, final int height) {

        BufferedImage bdest = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D g = bdest.createGraphics();
        AffineTransform at = AffineTransform.getScaleInstance((double) bdest.getWidth() / bsrc.getWidth(),
            (double) bdest.getHeight() / bsrc.getHeight());
        g.drawRenderedImage(bsrc, at);
        g.dispose();

        return bdest;
    }
 
Example 32
Project: TrakEM2   File: M.java    License: GNU General Public License v3.0 5 votes vote down vote up
/** Returns the approximated area of the given Area object; Loader can be null; if not, it's used to secure memory space. */
static public final double measureArea(Area area, final Loader loader) {
	double sum = 0;
	try {
		Rectangle bounds = area.getBounds();
		double scale = 1;
		if (bounds.width > 2048 || bounds.height > 2048) { // TODO value 2048 should be reconsidered as a project property
			scale = 2048.0 / bounds.width;
		}
		if (0 == scale) {
			Utils.log("Can't measure: area too large, out of scale range for approximation.");
			return sum;
		}
		final AffineTransform at = new AffineTransform();
		at.translate(-bounds.x, -bounds.y);
		at.scale(scale, scale);
		area = area.createTransformedArea(at);
		bounds = area.getBounds();
		if (0 == bounds.width || 0 == bounds.height) {
			Utils.log("Can't measure: area too large, approximates zero.");
			return sum;
		}
		if (null != loader) loader.releaseToFit(bounds.width * bounds.height * 3);
		final BufferedImage bi = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_BYTE_INDEXED);
		final Graphics2D g = bi.createGraphics();
		g.setColor(Color.white);
		g.fill(area);
		final byte[] pixels = ((DataBufferByte)bi.getRaster().getDataBuffer()).getData(); // buffer.getData();
		for (int i=pixels.length-1; i>-1; i--) {
			//if (255 == (pixels[i]&0xff)) sum++;
			if (0 != pixels[i]) sum++;
		}
		bi.flush();
		g.dispose();
		if (1 != scale) sum = sum / (scale * scale);
	} catch (final Throwable e) {
		IJError.print(e);
	}
	return sum;
}
 
Example 33
Project: TencentKona-8   File: PrinterGraphicsConfig.java    License: GNU General Public License v2.0 5 votes vote down vote up
public PrinterGraphicsConfig(String printerID, AffineTransform deviceTx,
                             int pageWid, int pageHgt) {
    this.pageWidth = pageWid;
    this.pageHeight = pageHgt;
    this.deviceTransform = deviceTx;
    this.gd = new PrinterGraphicsDevice(this, printerID);
}
 
Example 34
Project: jdk8u_jdk   File: D3DBlitLoops.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void Transform(SurfaceData src, SurfaceData dst,
                      Composite comp, Region clip,
                      AffineTransform at, int hint,
                      int sx, int sy, int dx, int dy, int w, int h)
{
    D3DBlitLoops.Blit(src, dst,
                      comp, clip, at, hint,
                      sx, sy, sx+w, sy+h,
                      dx, dy, dx+w, dy+h,
                      typeval, false);
}
 
Example 35
Project: jdk8u-dev-jdk   File: TransformHelper.java    License: GNU General Public License v2.0 5 votes vote down vote up
public native void Transform(MaskBlit output,
SurfaceData src, SurfaceData dst,
Composite comp, Region clip,
AffineTransform itx, int txtype,
int sx1, int sy1, int sx2, int sy2,
int dx1, int dy1, int dx2, int dy2,
int edges[], int dxoff, int dyoff);
 
Example 36
Project: jdk8u-jdk   File: CFont.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected FontStrike createStrike(FontStrikeDesc desc) {
    if (isFakeItalic) {
        desc = new FontStrikeDesc(desc);
        desc.glyphTx.concatenate(AffineTransform.getShearInstance(-0.2, 0));
    }
    return new CStrike(this, desc);
}
 
Example 37
Project: jdk8u-dev-jdk   File: RadialGradientPaint.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static AffineTransform createGradientTransform(Rectangle2D r) {
    double cx = r.getCenterX();
    double cy = r.getCenterY();
    AffineTransform xform = AffineTransform.getTranslateInstance(cx, cy);
    xform.scale(r.getWidth()/2, r.getHeight()/2);
    xform.translate(-cx, -cy);
    return xform;
}
 
Example 38
Project: openjdk-8-source   File: RasterPrinterJob.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
  * save graphics state of a PathGraphics for later redrawing
  * of part of page represented by the region in that state
  */

public void saveState(AffineTransform at, Shape clip,
                      Rectangle2D region, double sx, double sy) {
    GraphicsState gstate = new GraphicsState();
    gstate.theTransform = at;
    gstate.theClip = clip;
    gstate.region = region;
    gstate.sx = sx;
    gstate.sy = sy;
    redrawList.add(gstate);
}
 
Example 39
Project: ccu-historian   File: ShapeUtilities.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates and returns a translated shape.
 *
 * @param shape  the shape (<code>null</code> not permitted).
 * @param transX  the x translation (in Java2D space).
 * @param transY  the y translation (in Java2D space).
 *
 * @return The translated shape.
 */
public static Shape createTranslatedShape(final Shape shape,
                                          final double transX,
                                          final double transY) {
    if (shape == null) {
        throw new IllegalArgumentException("Null 'shape' argument.");
    }
    final AffineTransform transform = AffineTransform.getTranslateInstance(
            transX, transY);
    return transform.createTransformedShape(shape);
}
 
Example 40
Project: openjdk-jdk8u-backup   File: StandardGlyphVector.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Ensure that the positions array exists and holds position data.
 * If the array is null, this allocates it and sets default positions.
 */
private void initPositions() {
    if (positions == null) {
        setFRCTX();

        positions = new float[glyphs.length * 2 + 2];

        Point2D.Float trackPt = null;
        float track = getTracking(font);
        if (track != 0) {
            track *= font.getSize2D();
            trackPt = new Point2D.Float(track, 0); // advance delta
        }

        Point2D.Float pt = new Point2D.Float(0, 0);
        if (font.isTransformed()) {
            AffineTransform at = font.getTransform();
            at.transform(pt, pt);
            positions[0] = pt.x;
            positions[1] = pt.y;

            if (trackPt != null) {
                at.deltaTransform(trackPt, trackPt);
            }
        }
        for (int i = 0, n = 2; i < glyphs.length; ++i, n += 2) {
            getGlyphStrike(i).addDefaultGlyphAdvance(glyphs[i], pt);
            if (trackPt != null) {
                pt.x += trackPt.x;
                pt.y += trackPt.y;
            }
            positions[n] = pt.x;
            positions[n+1] = pt.y;
        }
    }
}