Java Code Examples for java.awt.Graphics2D#getTransform()

The following examples show how to use java.awt.Graphics2D#getTransform() . 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
Source Project: btdex   File: RotatingIcon.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void paintIcon( Component c, Graphics g, int x, int y ) {
	rotatingTimer.stop();
	Graphics2D g2 = (Graphics2D )g.create();
	int cWidth = delegateIcon.getIconWidth() / 2;
	int cHeight = delegateIcon.getIconHeight() / 2;
	Rectangle r = new Rectangle(x, y, delegateIcon.getIconWidth(), delegateIcon.getIconHeight());
	g2.setClip(r);
	AffineTransform original = g2.getTransform();
	AffineTransform at = new AffineTransform();
	at.concatenate(original);
	at.rotate(Math.toRadians( angleInDegrees ), x + cWidth, y + cHeight);
	g2.setTransform(at);
	
	// trying to make it look better
	g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) ;
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC) ;
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY) ;

	delegateIcon.paintIcon(c, g2, x, y);
	g2.setTransform(original);
	rotatingTimer.start();
}
 
Example 2
/**
 * Draws the attributed string at {@code (textX, textY)}, rotated by 
 * the specified angle about {@code (rotateX, rotateY)}.
 * 
 * @param text  the attributed string ({@code null} not permitted).
 * @param g2  the graphics output target ({@code null} not permitted).
 * @param textX  the x-coordinate for the text alignment point.
 * @param textY  the y-coordinate for the text alignment point.
 * @param angle  the rotation angle (in radians).
 * @param rotateX  the x-coordinate for the rotation point.
 * @param rotateY  the y-coordinate for the rotation point.
 * 
 * @return The text bounds (never {@code null}).
 * 
 * @since 1.2
 */
public static Shape drawRotatedString(AttributedString text, Graphics2D g2, 
        float textX, float textY, double angle, float rotateX, 
        float rotateY) {
    
    Args.nullNotPermitted(text, "text");
    AffineTransform saved = g2.getTransform();
    AffineTransform rotate = AffineTransform.getRotateInstance(angle, 
            rotateX, rotateY);
    g2.transform(rotate);
    TextLayout tl = new TextLayout(text.getIterator(),
                g2.getFontRenderContext());
    Rectangle2D rect = tl.getBounds();
    tl.draw(g2, textX, textY);
    g2.setTransform(saved);
    return rotate.createTransformedShape(rect);
}
 
Example 3
Source Project: lams   File: CharBox.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void draw(Graphics2D g2, float x, float y) {
    drawDebug(g2, x, y);
    AffineTransform at = g2.getTransform();
    g2.translate(x, y);
    Font font = FontInfo.getFont(cf.fontId);

    if (Math.abs(size - TeXFormula.FONT_SCALE_FACTOR) > TeXFormula.PREC) {
        g2.scale(size / TeXFormula.FONT_SCALE_FACTOR,
                 size / TeXFormula.FONT_SCALE_FACTOR);
    }

    if (g2.getFont() != font) {
        g2.setFont(font);
    }

    arr[0] = cf.c;
    g2.drawChars(arr, 0, 1, 0, 0);
    g2.setTransform(at);
}
 
Example 4
/**
 * Draws the attributed string at <code>(textX, textY)</code>, rotated by 
 * the specified angle about <code>(rotateX, rotateY)</code>.
 * 
 * @param text  the attributed string (<code>null</code> not permitted).
 * @param g2  the graphics output target.
 * @param textX  the x-coordinate for the text.
 * @param textY  the y-coordinate for the text.
 * @param angle  the rotation angle (in radians).
 * @param rotateX  the x-coordinate for the rotation point.
 * @param rotateY  the y-coordinate for the rotation point.
 * 
 * @since 1.0.16
 */
public static void drawRotatedString(AttributedString text, Graphics2D g2, 
        float textX, float textY, double angle, float rotateX, 
        float rotateY) {
    ParamChecks.nullNotPermitted(text, "text");

    AffineTransform saved = g2.getTransform();
    AffineTransform rotate = AffineTransform.getRotateInstance(angle, 
            rotateX, rotateY);
    g2.transform(rotate);
    TextLayout tl = new TextLayout(text.getIterator(),
                g2.getFontRenderContext());
    tl.draw(g2, textX, textY);
    
    g2.setTransform(saved);        
}
 
Example 5
/**
 * Draws a path shape on the map.
 * @param g2d the graphics2D context.
 * @param color the color to display the path shape.
 */
private void drawPathShape(Path2D pathShape, Graphics2D g2d, Color color) {

    // Save original graphics transforms.
    AffineTransform saveTransform = g2d.getTransform();

    // Determine bounds.
    Rectangle2D bounds = pathShape.getBounds2D();

    // Determine transform information.
    double boundsPosX = bounds.getX() * scale;
    double boundsPosY = bounds.getY() * scale;
    double centerX = bounds.getWidth() * scale / 2D;
    double centerY = bounds.getHeight() * scale / 2D;
    double translationX = (-1D * bounds.getCenterX() * scale) - centerX - boundsPosX;
    double translationY = (-1D * bounds.getCenterY() * scale) - centerY - boundsPosY;
    double facingRadian = Math.PI;

    // Apply graphic transforms for path shape.
    AffineTransform newTransform = new AffineTransform();
    newTransform.translate(translationX, translationY);
    newTransform.rotate(facingRadian, centerX + boundsPosX, centerY + boundsPosY);

    // Draw filled path shape.
    newTransform.scale(scale, scale);
    g2d.transform(newTransform);
    g2d.setColor(color);
    g2d.fill(pathShape);

    // Restore original graphic transforms.
    g2d.setTransform(saveTransform);
}
 
Example 6
/** Paints the transformation handles and a bounding box around all selected. */
@Override
      public void paintOnTop(final Graphics2D g, final Display display, final Rectangle srcRect, final double magnification) {
	final Stroke original_stroke = g.getStroke();
	final AffineTransform original = g.getTransform();
	g.setTransform(new AffineTransform());
	if (!rotating) {
		//Utils.log("box painting: " + box);

		// 30 pixel line, 10 pixel gap, 10 pixel line, 10 pixel gap
		//float mag = (float)magnification;
		final float[] dashPattern = { 30, 10, 10, 10 };
		g.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10, dashPattern, 0));
		g.setColor(Color.yellow);
		// paint box
		//g.drawRect(box.x, box.y, box.width, box.height);
		g.draw(original.createTransformedShape(box));
		g.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
		// paint handles for scaling (boxes) and rotating (circles), and floater
		for (int i=0; i<handles.length; i++) {
			handles[i].paint(g, srcRect, magnification);
		}
	} else {
		g.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
		RO.paint(g, srcRect, magnification);
		((RotationHandle)RO).paintMoving(g, srcRect, magnification, display.getCanvas().getCursorLoc());
	}

	if (null != affine_handles) {
		for (final AffinePoint ap : affine_handles) {
			ap.paint(g);
		}
	}

	g.setTransform(original);
	g.setStroke(original_stroke);
}
 
Example 7
public void render(
Graphics2D graphics,double viewwidth,double viewheight,double viewscale,
double viewoffsetx,double viewoffsety){
//get our minimal rectangular kisrhombille grid tile
int tilewidth=(int)(viewscale*2.0*Math.sqrt(3.0))+1;  
int tileheight=(int)(viewscale*6.0);
//calculate offset for putting grid origin at view center
double 
  littleoffsetx=((viewwidth/2.0)%(double)tilewidth),
  littleoffsety=((viewheight/2.0)%(double)tileheight);
//calculate scaled offset for view offset
double 
  scaledviewoffsetx=-((viewoffsetx*viewscale)%tilewidth),
  scaledviewoffsety=(viewoffsety*viewscale)%tileheight;
//set the transform, holding the old transform so we can restore it later
AffineTransform oldtransform=graphics.getTransform();
graphics.transform(AffineTransform.getTranslateInstance(
  scaledviewoffsetx+littleoffsetx,
  scaledviewoffsety+littleoffsety));
//paint tiles
BufferedImage itile=getTileImage(tilewidth,tileheight,viewscale);
int 
  tilexcount=(int)(viewwidth/tilewidth)+5,
  tileycount=(int)(viewheight/tileheight)+5;
for(int x=0;x<tilexcount;x++){
  for(int y=0;y<tileycount;y++){
    graphics.drawImage(itile,null,x*tilewidth-tilewidth*2,y*tileheight-tileheight*2);}}
//restore old transform
graphics.setTransform(oldtransform);}
 
Example 8
private void drawText(Graphics2D g, ChartText3D text, float x, float y) {
    AffineTransform tempTrans = g.getTransform();
    //AffineTransform myTrans = new AffineTransform();
    AffineTransform myTrans = (AffineTransform)tempTrans.clone();
    myTrans.translate(x, y);
    if (text.getZDir() != null) {
        text.updateAngle(projector);
        float angle = text.getAngle() + 90;
        myTrans.rotate(-angle * Math.PI / 180);
    }
    g.setTransform(myTrans);
    g.setFont(text.getFont());
    g.setColor(text.getColor());
    x = 0;
    y = 0;
    switch (text.getYAlign()) {
        case TOP:
            y += g.getFontMetrics(g.getFont()).getAscent();
            break;
        case CENTER:
            y += g.getFontMetrics(g.getFont()).getAscent() / 2;
            break;
    }
    String s = text.getText();
    Dimension labSize = Draw.getStringDimension(s, g);
    switch (text.getXAlign()) {
        case RIGHT:
            x = x - labSize.width;
            break;
        case CENTER:
            x = x - labSize.width / 2;
            break;
    }
    Draw.drawString(g, s, x, y);
    g.setTransform(tempTrans);
}
 
Example 9
Source Project: pdfxtk   File: GraphEdge.java    License: Apache License 2.0 5 votes vote down vote up
public void paintMarkers(Graphics g) {
   if(polyline != null && markers.length > 0) {
     Graphics2D      g2      = (Graphics2D)g;
     AffineTransform svTrans = g2.getTransform();
     for(int i = 0; i < markers.length; i++) {
g2.transform(mtrans[i]);
markers[i].paint(g, markerwidth[i]);
g2.setTransform(svTrans);
     } 
   }
 }
 
Example 10
Source Project: osp   File: ElementImage.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void drawIt(Graphics2D _g2) {
  if(image==null) {
    return;
  }
  if(angle!=0.0) {
    AffineTransform originalTransform = _g2.getTransform();
    transform.setTransform(originalTransform);
    transform.rotate(-angle, pixel[0], pixel[1]);
    _g2.setTransform(transform);
    _g2.drawImage(image, (int) (pixel[0]-pixelSize[0]/2), (int) (pixel[1]-pixelSize[1]/2), (int) pixelSize[0], (int) pixelSize[1], null);
    _g2.setTransform(originalTransform);
  } else {
    _g2.drawImage(image, (int) (pixel[0]-pixelSize[0]/2), (int) (pixel[1]-pixelSize[1]/2), (int) pixelSize[0], (int) pixelSize[1], null);
  }
}
 
Example 11
/**
 * Paints a chart with scaling options
 * 
 * @param chart
 * @param info
 * @param out
 * @param width
 * @param height
 * @param resolution
 * @return BufferedImage of a given chart with scaling to resolution
 * @throws IOException
 */
private static BufferedImage paintScaledChartToBufferedImage(JFreeChart chart,
    ChartRenderingInfo info, OutputStream out, int width, int height, int resolution,
    int bufferedIType) throws IOException {
  Args.nullNotPermitted(out, "out");
  Args.nullNotPermitted(chart, "chart");

  double scaleX = resolution / 72.0;
  double scaleY = resolution / 72.0;

  double desiredWidth = width * scaleX;
  double desiredHeight = height * scaleY;
  double defaultWidth = width;
  double defaultHeight = height;
  boolean scale = false;

  // get desired width and height from somewhere then...
  if ((scaleX != 1) || (scaleY != 1)) {
    scale = true;
  }

  BufferedImage image = new BufferedImage((int) desiredWidth, (int) desiredHeight, bufferedIType);
  Graphics2D g2 = image.createGraphics();

  if (scale) {
    AffineTransform saved = g2.getTransform();
    g2.transform(AffineTransform.getScaleInstance(scaleX, scaleY));
    chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth, defaultHeight), info);
    g2.setTransform(saved);
    g2.dispose();
  } else {
    chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth, defaultHeight), info);
  }
  return image;
}
 
Example 12
/**
 * A utility method for drawing rotated text.
 * <P>
 * A common rotation is -Math.PI/2 which draws text 'vertically' (with the
 * top of the characters on the left).
 *
 * @param text  the text.
 * @param g2  the graphics device.
 * @param textX  the x-coordinate for the text (before rotation).
 * @param textY  the y-coordinate for the text (before rotation).
 * @param angle  the angle of the (clockwise) rotation (in radians).
 * @param rotateX  the point about which the text is rotated.
 * @param rotateY  the point about which the text is rotated.
 */
public static void drawRotatedString(String text, Graphics2D g2,
        float textX, float textY, 
        double angle, float rotateX, float rotateY) {

    if ((text == null) || (text.equals(""))) {
        return;
    }
    if (angle == 0.0) {
        drawAlignedString(text, g2, textY, textY, TextAnchor.BASELINE_LEFT);
        return;
    }
    
    AffineTransform saved = g2.getTransform();
    AffineTransform rotate = AffineTransform.getRotateInstance(
            angle, rotateX, rotateY);
    g2.transform(rotate);

    if (useDrawRotatedStringWorkaround) {
        // workaround for JDC bug ID 4312117 and others...
        TextLayout tl = new TextLayout(text, g2.getFont(),
                g2.getFontRenderContext());
        tl.draw(g2, textX, textY);
    }
    else {
        if (!drawStringsWithFontAttributes) {
            g2.drawString(text, textX, textY);
        } else {
            AttributedString as = new AttributedString(text, 
                    g2.getFont().getAttributes());
            g2.drawString(as.getIterator(), textX, textY);
        }
    }
    g2.setTransform(saved);

}
 
Example 13
/**
 * Draw the given rectangle onto the starmap.
 * @param g2 the graphics context
 * @param shape the shape
 * @param fill fill it?
 */
void drawShape(Graphics2D g2, Shape shape, boolean fill) {
	double zoom = getZoom();
	AffineTransform at = g2.getTransform();
	g2.translate(starmapRect.x, starmapRect.y);
	g2.scale(zoom, zoom);
	if (fill) {
		g2.fill(shape);
	} else {
		g2.draw(shape);
	}
	g2.setTransform(at);
}
 
Example 14
/**
 * Writes a scaled version of a chart to an output stream in PNG format.
 *
 * @param out  the output stream (<code>null</code> not permitted).
 * @param chart  the chart (<code>null</code> not permitted).
 * @param width  the unscaled chart width.
 * @param height  the unscaled chart height.
 * @param widthScaleFactor  the horizontal scale factor.
 * @param heightScaleFactor  the vertical scale factor.
 *
 * @throws IOException if there are any I/O problems.
 */
public static void writeScaledChartAsPNG(OutputStream out,
        JFreeChart chart, int width, int height, int widthScaleFactor,
        int heightScaleFactor) throws IOException {

    ParamChecks.nullNotPermitted(out, "out");
    ParamChecks.nullNotPermitted(chart, "chart");

    double desiredWidth = width * widthScaleFactor;
    double desiredHeight = height * heightScaleFactor;
    double defaultWidth = width;
    double defaultHeight = height;
    boolean scale = false;

    // get desired width and height from somewhere then...
    if ((widthScaleFactor != 1) || (heightScaleFactor != 1)) {
        scale = true;
    }

    double scaleX = desiredWidth / defaultWidth;
    double scaleY = desiredHeight / defaultHeight;

    BufferedImage image = new BufferedImage((int) desiredWidth,
            (int) desiredHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = image.createGraphics();

    if (scale) {
        AffineTransform saved = g2.getTransform();
        g2.transform(AffineTransform.getScaleInstance(scaleX, scaleY));
        chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth,
                defaultHeight), null, null);
        g2.setTransform(saved);
        g2.dispose();
    }
    else {
        chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth,
                defaultHeight), null, null);
    }
    out.write(encodeAsPNG(image));

}
 
Example 15
private void modeSpecificDrawLine( Graphics2D g2, String line,
                                   int baseX, int baseY ) {
    /// ABP - keep track of old tform, restore it later
    AffineTransform oldTx = null;
    oldTx = g2.getTransform();
    g2.translate( baseX, baseY );
    g2.transform( getAffineTransform( g2Transform ) );

    switch ( drawMethod ) {
      case DRAW_STRING:
        g2.drawString( line, 0, 0 );
        break;
      case DRAW_CHARS:
        g2.drawChars( line.toCharArray(), 0, line.length(), 0, 0 );
        break;
      case DRAW_BYTES:
        try {
            byte lineBytes[] = line.getBytes( "ISO-8859-1" );
            g2.drawBytes( lineBytes, 0, lineBytes.length, 0, 0 );
        }
        catch ( Exception e ) {
            e.printStackTrace();
        }
        break;
      case DRAW_GLYPHV:
        GlyphVector gv =
          testFont.createGlyphVector( g2.getFontRenderContext(), line );
        g2.drawGlyphVector( gv, (float) 0, (float) 0 );
        break;
      case TL_DRAW:
        TextLayout tl = new TextLayout( line, testFont,
                                        g2.getFontRenderContext() );
        tl.draw( g2, (float) 0, (float) 0 );
        break;
      case GV_OUTLINE:
        GlyphVector gvo =
          testFont.createGlyphVector( g2.getFontRenderContext(), line );
        g2.draw( gvo.getOutline( (float) 0, (float) 0 ));
        break;
      case TL_OUTLINE:
        TextLayout tlo =
          new TextLayout( line, testFont,
                          g2.getFontRenderContext() );
        AffineTransform at = new AffineTransform();
        g2.draw( tlo.getOutline( at ));
    }

    /// ABP - restore old tform
    g2.setTransform ( oldTx );

}
 
Example 16
@Override
public void draw(Graphics2D g2) {
	onResize();
	if (fadeIndex >= 0 && fadeIndex * 2 < FADE_MAX) {
		g2.setColor(new Color(0, 0, 0, fadeIndex * 2f / FADE_MAX));
	} else {
		g2.setColor(Color.BLACK);
	}
	g2.fillRect(0, 0, getInnerWidth(), getInnerHeight());
	if (frontBuffer != null) {
		swapLock.lock();
		try {
			RenderTools.setInterpolation(g2, true);
			if (config.movieScale) {
				double sx = getInnerWidth() / 640.0;
				double sy = getInnerHeight() / 480.0;
				double scalex = Math.min(sx, sy);
				double scaley = scalex;
				// center the image
				AffineTransform save0 = g2.getTransform();
				double dx = getInnerWidth() - (640 * scalex);
				double dy = getInnerHeight() - (480 * scaley); 
				g2.translate(dx / 2,
						dy / 2);
				
				g2.drawImage(frontBuffer, 0, 0, (int)(640 * scalex), (int)(480 * scaley), null);
				g2.setTransform(save0);
				if (label != null && config.subtitles) {
					paintLabel(g2, 0, 0, getInnerWidth(), getInnerHeight());
				}
			} else {
				g2.drawImage(frontBuffer, movieRect.x, movieRect.y, 
						movieRect.width, movieRect.height, null);
				if (label != null && config.subtitles) {
					paintLabel(g2, movieRect.x, movieRect.y, movieRect.width, movieRect.height);
				}
						}
			RenderTools.setInterpolation(g2, false);
		} finally {
			swapLock.unlock();
		}
	}
	if (fadeIndex * 2 >= FADE_MAX) {
		g2.setColor(new Color(0, 0, 0, (FADE_MAX - fadeIndex) * 2f / FADE_MAX));
		g2.fillRect(0, 0, getInnerWidth(), getInnerHeight());
	}
}
 
Example 17
/**
 * Writes a scaled version of a chart to an output stream in PNG format.
 *
 * @param out  the output stream (<code>null</code> not permitted).
 * @param chart  the chart (<code>null</code> not permitted).
 * @param width  the unscaled chart width.
 * @param height  the unscaled chart height.
 * @param widthScaleFactor  the horizontal scale factor.
 * @param heightScaleFactor  the vertical scale factor.
 *
 * @throws IOException if there are any I/O problems.
 */
public static void writeScaledChartAsPNG(OutputStream out,
        JFreeChart chart, int width, int height, int widthScaleFactor,
        int heightScaleFactor) throws IOException {

    ParamChecks.nullNotPermitted(out, "out");
    ParamChecks.nullNotPermitted(chart, "chart");

    double desiredWidth = width * widthScaleFactor;
    double desiredHeight = height * heightScaleFactor;
    double defaultWidth = width;
    double defaultHeight = height;
    boolean scale = false;

    // get desired width and height from somewhere then...
    if ((widthScaleFactor != 1) || (heightScaleFactor != 1)) {
        scale = true;
    }

    double scaleX = desiredWidth / defaultWidth;
    double scaleY = desiredHeight / defaultHeight;

    BufferedImage image = new BufferedImage((int) desiredWidth,
            (int) desiredHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = image.createGraphics();

    if (scale) {
        AffineTransform saved = g2.getTransform();
        g2.transform(AffineTransform.getScaleInstance(scaleX, scaleY));
        chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth,
                defaultHeight), null, null);
        g2.setTransform(saved);
        g2.dispose();
    }
    else {
        chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth,
                defaultHeight), null, null);
    }
    out.write(encodeAsPNG(image));

}
 
Example 18
Source Project: netbeans   File: VectorIcon.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public final void paintIcon(Component c, Graphics g0, int x, int y) {
    final Graphics2D g2 = createGraphicsWithRenderingHintsConfigured(g0);
    try {
        // Make sure the subclass can't paint outside its stated dimensions.
        g2.clipRect(x, y, getIconWidth(), getIconHeight());
        g2.translate(x, y);
        /**
         * On HiDPI monitors, the Graphics object will have a default transform that maps
         * logical pixels, like those you'd pass to Graphics.drawLine, to a higher number of
         * device pixels on the screen. For instance, painting a line 10 pixels long on the
         * current Graphics object would actually produce a line 20 device pixels long on a
         * MacOS retina screen, which has a DPI scaling factor of 2.0. On Windows 10, many
         * different scaling factors may be encountered, including non-integral ones such as
         * 1.5. Detect the scaling factor here so we can use it to inform the drawing routines.
         */
        final double scaling;
        final AffineTransform tx = g2.getTransform();
        int txType = tx.getType();
        if (txType == AffineTransform.TYPE_UNIFORM_SCALE ||
            txType == (AffineTransform.TYPE_UNIFORM_SCALE | AffineTransform.TYPE_TRANSLATION))
        {
            scaling = tx.getScaleX();
        } else {
            // Unrecognized transform type. Don't do any custom scaling handling.
            paintIcon(c, g2, getIconWidth(), getIconHeight(), 1.0);
            return;
        }
        /* When using a non-integral scaling factor, such as 175%, preceding Swing components
        often end up being a non-integral number of device pixels tall or wide. This will cause
        our initial position to be "off the grid" with respect to device pixels, causing blurry
        graphics even if we subsequently take care to use only integral numbers of device pixels
        during painting. Fix this here by consuming a little bit of the top and left of the
        icon's dimensions to offset any error. */
        // The initial position, in device pixels.
        final double previousDevicePosX = tx.getTranslateX();
        final double previousDevicePosY = tx.getTranslateY();
        /* The new, aligned position, after a small portion of the icon's dimensions may have
        been consumed to correct it. */
        final double alignedDevicePosX = Math.ceil(previousDevicePosX);
        final double alignedDevicePosY = Math.ceil(previousDevicePosY);
        // Use the aligned position.
        g2.setTransform(new AffineTransform(
            1, 0, 0, 1, alignedDevicePosX, alignedDevicePosY));
        /* The portion of the icon's dimensions that was consumed to correct any initial
        translation misalignment, in device pixels. May be zero. */
        final double transDeviceAdjX = alignedDevicePosX - previousDevicePosX;
        final double transDeviceAdjY = alignedDevicePosY - previousDevicePosY;
        /* Now calculate the dimensions available for painting, also aligned to an integral
        number of device pixels. */
        final int deviceWidth  = (int) Math.floor(getIconWidth()  * scaling - transDeviceAdjX);
        final int deviceHeight = (int) Math.floor(getIconHeight() * scaling - transDeviceAdjY);
        paintIcon(c, g2, deviceWidth, deviceHeight, scaling);
    } finally {
        g2.dispose();
    }
}
 
Example 19
Source Project: netbeans   File: ImageUtilities.java    License: Apache License 2.0 4 votes vote down vote up
public void paintIcon(Component c, Graphics g, int x, int y) {
    if (delegateIcon != null) {
        delegateIcon.paintIcon(c, g, x, y);
    } else {
        /* There is no scalable delegate icon available. On HiDPI displays, this means that
        original low-resolution icons will need to be scaled up to a higher resolution. Do a
        few tricks here to improve the quality of the scaling. See NETBEANS-2614 and the
        before/after screenshots that are attached to said JIRA ticket. */
        Graphics2D g2 = (Graphics2D) g.create();
        try {
            final AffineTransform tx = g2.getTransform();
            final int txType = tx.getType();
            final double scale;
            if (txType == AffineTransform.TYPE_UNIFORM_SCALE ||
                txType == (AffineTransform.TYPE_UNIFORM_SCALE | AffineTransform.TYPE_TRANSLATION))
            {
              scale = tx.getScaleX();
            } else {
              scale = 1.0;
            }
            if (scale != 1.0) {
                /* The default interpolation mode is nearest neighbor. Use bicubic
                interpolation instead, which looks better, especially with non-integral
                HiDPI scaling factors (e.g. 150%). Even for an integral 2x scaling factor
                (used by all Retina displays on MacOS), the blurred appearance of bicubic
                scaling ends up looking better on HiDPI displays than the blocky appearance
                of nearest neighbor. */
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
                g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                /* For non-integral scaling factors, we frequently encounter non-integral
                device pixel positions. For instance, with a 150% scaling factor, the
                logical pixel position (7,0) would map to device pixel position (10.5,0).
                On such scaling factors, icons look a lot better if we round the (x,y)
                translation to an integral number of device pixels before painting. */
                g2.setTransform(new AffineTransform(scale, 0, 0, scale,
                        (int) tx.getTranslateX(), (int) tx.getTranslateY()));
            }
            g2.drawImage(this, x, y, null);
        } finally {
            g2.dispose();
        }
    }
}
 
Example 20
void paintLinkText(Graphics2D g, Link link, boolean bClip) {
    Dimension size = getSize();
    Node n1 = link.getFrom();
    Node n2 = link.getTo();


    Point2D p1 = n1.getPoint();
    Point2D p2 = n2.getPoint();

    if(p1 != null && p2 != null) {
      Color c1 = Color.white;
      Color c2 = Color.black;

      double cx = (p1.getX() + p2.getX()) / 2;
      double cy = (p1.getY() + p2.getY()) / 2;

      // double mx = cx - mousePoint.getX();
      // double my = cy - mousePoint.getY();
      // double dist = Math.sqrt(mx * mx + my * my);

      double k = 1.0 / (1 + link.getDepth());
      if(link.getDepth() < 10 && size.width > 50) {
        float textScale = Math.min(1f, (float)(k * 1.8));

        AffineTransform trans = g.getTransform();

        String s = link.toString();

        FontMetrics fm = g.getFontMetrics();

        Rectangle2D r = fm.getStringBounds(s, g);



        int pad = 2;

        double left = (cx-r.getWidth()/2) - pad;
        double top  = cy - (r.getHeight()/2) -pad;
//        double w    = r.getWidth() + 2 * pad;
//        double h    = r.getHeight() + 2 * pad;

        g.translate(left, top);
        g.scale(textScale, textScale);

        g.setColor(c1);
        g.drawString(s, 0, 0);
        g.setColor(c2);
        g.drawString(s, 1, 1);

        // paintString(g, link.toString(), 0, 0, bClip);

        g.setTransform(trans);

        /*
        g.translate((int)p2.getX(), (int)p2.getY());
        g.scale(textScale, textScale);

        paintString(g, n2.toString(), 0, 0, bClip);
        */

        g.setTransform(trans);
      }
    }
  }