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

The following examples show how to use java.awt.Graphics2D#clearRect() . 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 File: SSD1331Test.java    From diozero with MIT License 6 votes vote down vote up
public static void drawText(SsdOled oled) {
	Logger.info("Coloured text");
	int width = oled.getWidth();
	int height = oled.getHeight();
	BufferedImage image = new BufferedImage(width, height, oled.getNativeImageType());
	Graphics2D g2d = image.createGraphics();

	g2d.setBackground(Color.BLACK);
	g2d.clearRect(0, 0, width, height);
	
	g2d.setColor(Color.RED);
	g2d.drawString("Red", 10, 10);
	g2d.setColor(Color.GREEN);
	g2d.drawString("Green", 10, 20);
	g2d.setColor(Color.BLUE);
	g2d.drawString("Blue", 10, 30);
	
	oled.display(image);
	
	g2d.dispose();
	try {
		Thread.sleep(1000);
	} catch (InterruptedException e) {
	}
}
 
Example 2
Source File: CGLGraphicsConfig.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void flip(final LWComponentPeer<?, ?> peer, final Image backBuffer,
                 final int x1, final int y1, final int x2, final int y2,
                 final BufferCapabilities.FlipContents flipAction) {
    final Graphics g = peer.getGraphics();
    try {
        g.drawImage(backBuffer, x1, y1, x2, y2, x1, y1, x2, y2, null);
    } finally {
        g.dispose();
    }
    if (flipAction == BufferCapabilities.FlipContents.BACKGROUND) {
        final Graphics2D bg = (Graphics2D) backBuffer.getGraphics();
        try {
            bg.setBackground(peer.getBackground());
            bg.clearRect(0, 0, backBuffer.getWidth(null),
                         backBuffer.getHeight(null));
        } finally {
            bg.dispose();
        }
    }
}
 
Example 3
Source File: AltTabCrashTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void renderToBS() {
    width = getWidth();
    height = getHeight();

    do {
        Graphics2D g2d = (Graphics2D)bufferStrategy.getDrawGraphics();

        g2d.clearRect(0, 0, width, height);
        synchronized (balls) {
            for (Ball b : balls) {
                b.move();
                b.paint(g2d, null);
            }
        }
        g2d.dispose();
    } while (bufferStrategy.contentsLost() ||
            bufferStrategy.contentsRestored());
}
 
Example 4
Source File: AltTabCrashTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void renderToBS() {
    width = getWidth();
    height = getHeight();

    do {
        Graphics2D g2d = (Graphics2D)bufferStrategy.getDrawGraphics();

        g2d.clearRect(0, 0, width, height);
        synchronized (balls) {
            for (Ball b : balls) {
                b.move();
                b.paint(g2d, null);
            }
        }
        g2d.dispose();
    } while (bufferStrategy.contentsLost() ||
            bufferStrategy.contentsRestored());
}
 
Example 5
Source File: TestApplet.java    From Azzet with Open Software License 3.0 6 votes vote down vote up
public synchronized void paint(Graphics g) 
{
	long time = System.nanoTime();
	update( (time - currentTime) * 0.000000001f );
	currentTime = time;
	
	BufferedImage buffer = getBuffer();
	
	Graphics2D gr = buffer.createGraphics();
	gr.setColor( getBackground() );
	gr.clearRect( 0, 0, buffer.getWidth(), buffer.getHeight() );
	gr.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	
	draw( gr );
	
	g.drawImage( buffer, 0, 0, this );
}
 
Example 6
Source File: ImageAddBorder.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public cfData execute( cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException{
	cfImageData im	= getImage( _session, argStruct );
	
	int thickness	= getNamedIntParam(argStruct, "thickness", 0 );
	if ( thickness == 0 )
		throwException(_session, "please specify a thickness greater than zero (0)" );
	
	String bordertype = getNamedStringParam(argStruct, "type", "constant" ).trim();
	if ( !bordertype.equals("constant") && !bordertype.equals("zero") )	{
		throwException(_session, "type must be 'constant' or 'zero'" );
	}
	
	Color color;
	if ( bordertype.equals("zero") ){
		color = Color.black;
	}else{
		color	= colour.getColor( getNamedStringParam(argStruct, "color", "black") );
	}
	
	int targetWidth		= im.getWidth() + ( thickness*2 );
	int targetHeight	= im.getHeight() + ( thickness*2 );
	
	BufferedImage	img = im.getImage();
	int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
	BufferedImage tmp = new BufferedImage(targetWidth, targetHeight, type);
	Graphics2D g2 = tmp.createGraphics();
	
	g2.setBackground(color);
	g2.clearRect(0, 0, targetWidth, targetHeight );
	g2.translate(thickness, thickness);
	g2.drawRenderedImage(img, null);
	g2.dispose();

	im.setImage( tmp );
	
	return cfBooleanData.TRUE;
}
 
Example 7
Source File: NimbusEditorTabCellRenderer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void paintTabBackground (Graphics g, int index, Component c,
int x, int y, int w, int h) {

    Shape clip = g.getClip();
    NimbusEditorTabCellRenderer ren = (NimbusEditorTabCellRenderer) c;

    w +=1;
    boolean isPreviousTabSelected = ren.isPreviousTabSelected();
    if (isPreviousTabSelected) {
        g.setClip(x+1, y, w-1, h);
    }

    Object o = null;
    if (ren.isSelected()) {
        if (ren.isActive()) {
            o = UIManager.get("TabbedPane:TabbedPaneTab[MouseOver+Selected].backgroundPainter");
        } else {
            o = UIManager.get("TabbedPane:TabbedPaneTab[Selected].backgroundPainter");
        }
    } else {
        o = UIManager.get("TabbedPane:TabbedPaneTab[Enabled].backgroundPainter");
    }
    if ((o != null) && (o instanceof javax.swing.Painter)) {
        javax.swing.Painter painter = (javax.swing.Painter) o;
        BufferedImage bufIm = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bufIm.createGraphics();
        g2d.setBackground(UIManager.getColor("Panel.background"));
        g2d.clearRect(0, 0, w, h);
        painter.paint(g2d, null, w, h);
        g.drawImage(bufIm, x, y, null);
    }

    if (isPreviousTabSelected) {
        g.setClip(clip);
    }
}
 
Example 8
Source File: imageOps.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public static BufferedImage rotate(BufferedImage _origImg, int angle, Color bgColor) {
	// Convert the degrees to radians
	double radians = Math.toRadians(angle);

	// Determine the sin and cos of the angle
	double sin = Math.abs(Math.sin(radians));
	double cos = Math.abs(Math.cos(radians));

	// Store the original width and height of the image
	int w = _origImg.getWidth();
	int h = _origImg.getHeight();

	// Determine the width and height of the rotated image
	int neww = (int) Math.floor(w * cos + h * sin);
	int newh = (int) Math.floor(h * cos + w * sin);

	// Create a BufferedImage to store the rotated image
	GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
	GraphicsDevice gd = ge.getDefaultScreenDevice();
	GraphicsConfiguration gc = gd.getDefaultConfiguration();
	BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.OPAQUE);

	// Render the rotated image
	Graphics2D g = result.createGraphics();
	g.setBackground(bgColor);
	g.clearRect(0, 0, neww, newh);
	g.translate((neww - w) / 2, (newh - h) / 2);
	g.rotate(radians, w / 2, h / 2);
	g.drawRenderedImage(_origImg, null);
	g.dispose();

	// Return the rotated image
	return result;
}
 
Example 9
Source File: OffScreenImage.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private void initSurface(int width, int height) {
    Graphics2D g2 = createGraphics();
    try {
        g2.clearRect(0, 0, width, height);
    } finally {
        g2.dispose();
    }
}
 
Example 10
Source File: CrashPaintTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public PaintContext createContext(ColorModel cm,
                                  Rectangle deviceBounds,
                                  Rectangle2D userBounds,
                                  AffineTransform at,
                                  RenderingHints hints) {

    // Fill bufferedImage using
    final Graphics2D g2d = (Graphics2D) getImage().getGraphics();
    try {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setBackground(Color.PINK);
        g2d.clearRect(0, 0, size, size);

        g2d.setColor(Color.BLUE);
        g2d.drawRect(0, 0, size, size);

        g2d.fillOval(size / 10, size / 10,
                     size * 8 / 10, size * 8 / 10);

    } finally {
        g2d.dispose();
    }

    return super.createContext(cm, deviceBounds, userBounds, at, hints);
}
 
Example 11
Source File: NestedHierarchicalDisplayPanel.java    From constellation with Apache License 2.0 5 votes vote down vote up
@Override
public void paintComponent(Graphics g) {
    if (lines == null) {
        return;
    }

    Graphics2D g2 = (Graphics2D) g;
    g2.setBackground(new Color(44, 44, 44));
    g2.clearRect(0, 0, getWidth(), getHeight());

    // Draw each line.
    g2.setColor(Color.blue);
    for (int i = 0; i < lines.size(); i++) {
        g2.setColor(lines.get(i).color);
        // horizontal line
        g2.fillRect(HORIZONTAL_BORDER_SIZE, VERTICAL_GAP + lines.get(i).ystart, lines.get(i).xstop, lineThickness);
        // vertical line
        g2.fillRect(HORIZONTAL_BORDER_SIZE + lines.get(i).xstop, VERTICAL_GAP + lines.get(i).ystop, lineThickness, lines.get(i).ystart - lines.get(i).ystop + lineThickness);
    }

    g2.setColor(new Color(0xB0, 0xB0, 0xB0));
    int arrowTop = scrollManager.getViewport().getViewPosition().y;
    int arrowBottom = arrowTop + Math.min(neededHeight, scrollManager.getViewport().getExtentSize().height);
    int[] xpoints = {progress_x - 6, progress_x + 8, progress_x + 1};
    int[] ypoints_top = {arrowTop, arrowTop, arrowTop + 10};
    int[] ypoints_bottom = {arrowBottom, arrowBottom, arrowBottom - 10};
    g2.fillPolygon(xpoints, ypoints_top, 3);
    g2.fillPolygon(xpoints, ypoints_bottom, 3);
    g2.setColor(new Color(0xB0, 0xB0, 0xB0, 130));
    g2.fillRect(progress_x, 0, progressBarThickness, neededHeight);
}
 
Example 12
Source File: JFXRepresentation.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
/** Update background, using background color and grid information from model */
private void updateBackground()
{
    final WidgetColor background = model.propBackgroundColor().getValue();

    // Setting the "-fx-background:" of the root node propagates
    // to all child nodes in the scene graph.
    //
    //        if (isEditMode())
    //            model_root.setStyle("-fx-background: linear-gradient(from 0px 0px to 10px 10px, reflect, #D2A2A2 48%, #D2A2A2 2%, #D2D2A2 48% #D2D2A2 2%)");
    //        else
    //            model_root.setStyle("-fx-background: " + JFXUtil.webRGB(background));
    //
    // In edit mode, this results in error messages because the linear-gradient doesn't "work" for all nodes:
    //
    // javafx.scene.CssStyleHelper (calculateValue)
    // Caught java.lang.ClassCastException: javafx.scene.paint.LinearGradient cannot be cast to javafx.scene.paint.Color
    // while converting value for
    // '-fx-background-color' from rule '*.text-input' in stylesheet ..jfxrt.jar!/com/sun/javafx/scene/control/skin/modena/modena.bss
    // '-fx-effect' from rule '*.scroll-bar:vertical>*.increment-button>*.increment-arrow' in StyleSheet ...  jfxrt.jar!/com/sun/javafx/scene/control/skin/modena/modena.bss
    // '-fx-effect' from rule '*.scroll-bar:vertical>*.decrement-button>*.decrement-arrow' in stylesheet ... modena.bss
    // '-fx-effect' from rule '*.scroll-bar:horizontal>*.increment-button>*.increment-arrow' in stylesheet ... modena.bss
    //
    // In the runtime, the background color style is applied to for example the TextEntryRepresentation,
    // overriding its jfx_node.setBackground(..) setting.

    // Setting just the scroll body background to a plain color or grid image provides basic color control.
    // In edit mode, the horiz_bound, vert_bound lines and grid provide sufficient
    // visual indication of the display size.

    final Color backgroundColor = new Color(background.getRed(), background.getGreen(), background.getBlue());

    final boolean gridVisible = isEditMode() ? model.propGridVisible().getValue() : false;
    final int gridStepX = model.propGridStepX().getValue(),
              gridStepY = model.propGridStepY().getValue();
    final WidgetColor grid_rgb = model.propGridColor().getValue();
    final Color gridColor = new Color(grid_rgb.getRed(), grid_rgb.getGreen(), grid_rgb.getBlue());

    final BufferedImage image = new BufferedImage(gridStepX, gridStepY, BufferedImage.TYPE_INT_ARGB);
    final Graphics2D g2d = image.createGraphics();

    g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

    g2d.setBackground(backgroundColor);
    g2d.clearRect(0, 0, gridStepX, gridStepY);

    if (gridVisible)
    {
        g2d.setColor(gridColor);
        g2d.setStroke(new BasicStroke(GRID_LINE_WIDTH));
        g2d.drawLine(0, 0, gridStepX, 0);
        g2d.drawLine(0, 0, 0, gridStepY);
    }

    final WritableImage wimage = new WritableImage(gridStepX, gridStepY);
    SwingFXUtils.toFXImage(image, wimage);
    final ImagePattern pattern = new ImagePattern(wimage, 0, 0, gridStepX, gridStepY, false);
    widget_parent.setBackground(new Background(new BackgroundFill(pattern, CornerRadii.EMPTY, Insets.EMPTY)));
}
 
Example 13
Source File: CrashPaintTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String argv[]) {
    Locale.setDefault(Locale.US);

    // initialize j.u.l Looger:
    final Logger log = Logger.getLogger("sun.java2d.marlin");
    log.addHandler(new Handler() {
        @Override
        public void publish(LogRecord record) {
            Throwable th = record.getThrown();
            // detect any Throwable:
            if (th != null) {
                System.out.println("Test failed:\n" + record.getMessage());
                th.printStackTrace(System.out);

                throw new RuntimeException("Test failed: ", th);
            }
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    });

    // enable Marlin logging & internal checks:
    System.setProperty("sun.java2d.renderer.log", "true");
    System.setProperty("sun.java2d.renderer.useLogger", "true");
    System.setProperty("sun.java2d.renderer.doChecks", "true");

    // Force using thread-local storage:
    System.setProperty("sun.java2d.renderer.useThreadLocal", "true");
    // Force smaller pixelsize to force using array caches:
    System.setProperty("sun.java2d.renderer.pixelsize", "256");

    final int width = 300;
    final int height = 300;

    final BufferedImage image = new BufferedImage(width, height,
            BufferedImage.TYPE_INT_ARGB);

    final Graphics2D g2d = (Graphics2D) image.getGraphics();
    try {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        g2d.setBackground(Color.WHITE);
        g2d.clearRect(0, 0, width, height);

        final Ellipse2D.Double ellipse
            = new Ellipse2D.Double(0, 0, width, height);

        final Paint paint = new CustomPaint(100);

        for (int i = 0; i < 20; i++) {
            final long start = System.nanoTime();
            g2d.setPaint(paint);
            g2d.fill(ellipse);

            g2d.setColor(Color.GREEN);
            g2d.draw(ellipse);

            final long time = System.nanoTime() - start;
            System.out.println("paint: duration= " + (1e-6 * time) + " ms.");
        }

        if (SAVE_IMAGE) {
            try {
                final File file = new File("CrashPaintTest.png");
                System.out.println("Writing file: "
                        + file.getAbsolutePath());
                ImageIO.write(image, "PNG", file);
            } catch (IOException ex) {
                System.out.println("Writing file failure:");
                ex.printStackTrace();
            }
        }

        // Check image on few pixels:
        final Raster raster = image.getData();

        // 170, 175 = blue
        checkPixel(raster, 170, 175, Color.BLUE.getRGB());
        // 50, 50 = blue
        checkPixel(raster, 50, 50, Color.BLUE.getRGB());

        // 190, 110 = pink
        checkPixel(raster, 190, 110, Color.PINK.getRGB());
        // 280, 210 = pink
        checkPixel(raster, 280, 210, Color.PINK.getRGB());

    } finally {
        g2d.dispose();
    }
}
 
Example 14
Source File: CrashNaNTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static void testFillDefaultAt() {
    final int width = 400;
    final int height = 400;

    final BufferedImage image = new BufferedImage(width, height,
                                        BufferedImage.TYPE_INT_ARGB);

    final Graphics2D g2d = (Graphics2D) image.getGraphics();
    try {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                             RenderingHints.VALUE_ANTIALIAS_ON);

        g2d.setBackground(Color.WHITE);
        g2d.clearRect(0, 0, width, height);

        final Path2D.Double path = new Path2D.Double();
        path.moveTo(100, 100);

        for (int i = 0; i < 20000; i++) {
            path.lineTo(110 + 0.01 * i, 110);
            path.lineTo(111 + 0.01 * i, 100);
        }

        path.lineTo(NaN, 200);
        path.lineTo(200, 200);
        path.lineTo(200, NaN);
        path.lineTo(300, 300);
        path.lineTo(NaN, NaN);
        path.lineTo(100, 200);
        path.closePath();

        final Path2D.Double path2 = new Path2D.Double();
        path2.moveTo(0, 0);
        path2.lineTo(100, height);
        path2.lineTo(0, 200);
        path2.closePath();

        g2d.setColor(Color.BLUE);
        g2d.fill(path);
        g2d.setColor(Color.GREEN);
        g2d.fill(path2);

        g2d.setColor(Color.BLACK);
        g2d.draw(path);
        g2d.draw(path2);

        if (SAVE_IMAGE) {
            try {
                final File file = new File("CrashNaNTest-fill.png");
                System.out.println("Writing file: "
                                   + file.getAbsolutePath());
                ImageIO.write(image, "PNG", file);
            } catch (IOException ex) {
                System.out.println("Writing file failure:");
                ex.printStackTrace();
            }
        }

        // Check image on few pixels:
        final Raster raster = image.getData();

        checkPixel(raster, 200, 195, Color.BLUE.getRGB());
        checkPixel(raster, 105, 195, Color.BLUE.getRGB());
        checkPixel(raster, 286, 290, Color.BLUE.getRGB());

        checkPixel(raster, 108, 105, Color.WHITE.getRGB());
        checkPixel(raster, 205, 200, Color.WHITE.getRGB());

        checkPixel(raster, 5, 200, Color.GREEN.getRGB());

    } finally {
        g2d.dispose();
    }
}
 
Example 15
Source File: ScaleClipTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private static void testNegativeScale(final BufferedImage image, final SCALE_MODE mode) {

        final Graphics2D g2d = (Graphics2D) image.getGraphics();
        try {
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

            g2d.setBackground(Color.WHITE);
            g2d.clearRect(0, 0, SIZE, SIZE);

            g2d.setColor(Color.BLACK);

            // Bug in TransformingPathConsumer2D.adjustClipScale()
            // non ortho scale only
            final double scale = -1.0;

            final AffineTransform at;
            switch (mode) {
                default:
                case ORTHO:
                    at = AffineTransform.getScaleInstance(scale, scale);
                    break;
                case NON_ORTHO:
                    at = AffineTransform.getScaleInstance(scale, scale + 1e-5);
                    break;
                case COMPLEX:
                    at = AffineTransform.getScaleInstance(scale, scale);
                    at.concatenate(AffineTransform.getShearInstance(1e-4, 1e-4));
                    break;
            }
            g2d.setTransform(at);

            // Set cap/join to reduce clip margin:
            g2d.setStroke(new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));

            final Path2D p = new Path2D.Double();
            p.moveTo(scale * 10, scale * 10);
            p.lineTo(scale * (SIZE - 10), scale * (SIZE - 10));

            g2d.draw(p);

            if (SAVE_IMAGE) {
                try {
                    final File file = new File("ScaleClipTest-testNegativeScale-" + mode + ".png");

                    System.out.println("Writing file: " + file.getAbsolutePath());
                    ImageIO.write(image, "PNG", file);
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }

            // Check image:
            // 25, 25 = black
            checkPixel(image.getData(), 25, 25, Color.BLACK.getRGB());

        } finally {
            g2d.dispose();
        }
    }
 
Example 16
Source File: CrashTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private static void testHugeImage(final int width, final int height)
    throws ArrayIndexOutOfBoundsException
{
    System.out.println("---\n" + "testHugeImage: "
        + "width=" + width + ", height=" + height);

    final BasicStroke stroke = createStroke(2.5f, false, 0);

    // size > 24bits (exceed both tile and buckets arrays)
    System.out.println("image size = " + width + " x "+height);

    final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);

    final Graphics2D g2d = (Graphics2D) image.getGraphics();
    try {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

        g2d.setBackground(Color.WHITE);
        g2d.clearRect(0, 0, width, height);

        g2d.setStroke(stroke);
        g2d.setColor(Color.BLACK);

        final Path2D.Float path = new Path2D.Float(WIND_NON_ZERO, 32);
        path.moveTo(0, 0);
        path.lineTo(width, 0);
        path.lineTo(width, height);
        path.lineTo(0, height);
        path.lineTo(0, 0);

        final long start = System.nanoTime();

        g2d.draw(path);

        final long time = System.nanoTime() - start;

        System.out.println("paint: duration= " + (1e-6 * time) + " ms.");

        if (SAVE_IMAGE) {
            try {
                final File file = new File("CrashTest-huge-"
                    + width + "x" +height + ".bmp");

                System.out.println("Writing file: " + file.getAbsolutePath());
                ImageIO.write(image, "BMP", file);
            } catch (IOException ex) {
                System.out.println("Writing file failure:");
                ex.printStackTrace();
            }
        }
    } finally {
        g2d.dispose();
    }
}
 
Example 17
Source File: GagExampleMain.java    From JImageHash with MIT License 4 votes vote down vote up
private static BufferedImage createLegendImage() {
	// Create legend
	int legendHeight = 230;
	int legendWidth = 30;
	int rightXOffset = 30;

	int legendXOffset = 40;

	int legendYOffset = 30;

	Color[] lowerCol = ColorUtil.ColorPalette.getPalette(230 / 2, Color.web("#ff642b"), Color.web("#ffff7c"));
	Color[] higherCol = ColorUtil.ColorPalette.getPalette(230 / 2, Color.web("#ffff7c"), Color.GREEN);

	Color[] colors = new Color[lowerCol.length + higherCol.length];
	System.arraycopy(lowerCol, 0, colors, 0, lowerCol.length);
	System.arraycopy(higherCol, 0, colors, lowerCol.length, higherCol.length);

	BufferedImage bi = new BufferedImage(legendWidth + legendXOffset + rightXOffset, legendHeight + legendYOffset,
			0x1);

	Graphics2D gc = (Graphics2D) bi.getGraphics();
	gc.setBackground(java.awt.Color.white);
	gc.clearRect(0, 0, bi.getWidth(), bi.getHeight());

	FastPixel fp = FastPixel.create(bi);

	for (int y = legendYOffset; y < legendHeight + legendYOffset; y++) {
		Color curColor = colors[y - legendYOffset];
		for (int x = legendXOffset; x < legendWidth + legendXOffset; x++) {
			fp.setRed(x, y, (int) (curColor.getRed() * 255));
			fp.setGreen(x, y, (int) (curColor.getGreen() * 255));
			fp.setBlue(x, y, (int) (curColor.getBlue() * 255));
		}
	}

	// Draw a black border
	gc.setColor(java.awt.Color.black);
	gc.setStroke(new BasicStroke(1));
	gc.drawRect(legendXOffset, legendYOffset, legendWidth - 1, legendHeight - 1);

	// Print some text on the left side
	gc.setColor(java.awt.Color.black);

	// We want 10 labels
	int labels = 11;
	int lHalf = labels / 2;
	int yIncrement = (int) Math.round((bi.getHeight() - legendYOffset - 6) / (labels - 1));

	for (int j = 0, y = legendYOffset + 6; y <= bi.getHeight(); y = y + yIncrement, j++) {

		int probability = 0;
		if (j < lHalf + 1) {
			probability = 100 / lHalf * (lHalf - j);
		} else {
			probability = -(100 / lHalf * (lHalf - j));
		}

		gc.drawString(probability + "%", 0, y);
	}

	gc.drawString("Certainty", 0, 12);
	gc.drawString("0 Bit", legendXOffset + legendWidth + 5, legendYOffset + 6);
	gc.drawString("1 Bit", legendXOffset + legendWidth + 5, bi.getHeight() - 5);

	gc.dispose();

	return bi;
}
 
Example 18
Source File: TreeJPanel.java    From berkeleyparser with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void paintComponent(Graphics g) {
	Graphics2D g2 = (Graphics2D) g;
	// FontMetrics fM = pickFont(g2, tree, space);

	double width = width(tree, myFont);
	double height = height(tree, myFont);
	preferredX = (int) width;
	preferredY = (int) height;
	setSize(new Dimension(preferredX, preferredY));
	setPreferredSize(new Dimension(preferredX, preferredY));
	setMaximumSize(new Dimension(preferredX, preferredY));
	setMinimumSize(new Dimension(preferredX, preferredY));
	// setSize(new Dimension((int)Math.round(width),
	// (int)Math.round(height)));
	g2.setFont(myFont.getFont());

	Dimension space = getSize();
	double startX = 0.0;
	double startY = 0.0;
	if (HORIZONTAL_ALIGN == SwingConstants.CENTER) {
		startX = (space.getWidth() - width) / 2.0;
	}
	if (HORIZONTAL_ALIGN == SwingConstants.RIGHT) {
		startX = space.getWidth() - width;
	}
	if (VERTICAL_ALIGN == SwingConstants.CENTER) {
		startY = (space.getHeight() - height) / 2.0;
	}
	if (VERTICAL_ALIGN == SwingConstants.BOTTOM) {
		startY = space.getHeight() - height;
	}
	super.paintComponent(g);

	g2.setBackground(Color.white);
	g2.clearRect(0, 0, space.width, space.height);

	g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
			1.0f));
	g2.setPaint(Color.black);

	paintTree(tree, new Point2D.Double(startX, startY), g2, myFont);
}
 
Example 19
Source File: AbstractAreaEffect.java    From Pixelitor with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void apply(Graphics2D g, Shape clipShape, int width, int height) {
    // opacity support added by lbalazscs
    Composite savedComposite = g.getComposite();
    if(opacity < 1.0f){
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));
    }

    // create a rect to hold the bounds
    Rectangle2D clipShapeBounds = clipShape.getBounds2D();

    if(clipShapeBounds.isEmpty()) {
        // check added by lbalazscs
        return;
    }

    width = (int) (clipShapeBounds.getWidth() + clipShapeBounds.getX());
    height = (int) (clipShapeBounds.getHeight() + clipShapeBounds.getY());
    Rectangle effectBounds = new Rectangle(0, 0,
            (int) (width + getEffectWidth() * 2 + 1),
            (int) (height + getEffectWidth() * 2 + 1));

    if (effectBounds.isEmpty()) {
        // check added by lbalazscs
        // this can be empty even if the clip shape bounds is not
        // when the clip shape starts at large negative coordinates
        return;
    }

    // Apply the border glow effect
    if (isShapeMasked()) {
        BufferedImage clipImage = getClipImage(effectBounds);
        Graphics2D g2 = clipImage.createGraphics();

        // lbalazscs: moved here from getClipImage
        // in order to avoid two createGraphics calls
        g2.clearRect(0, 0, clipImage.getWidth(), clipImage.getHeight());

        try {
            // clear the buffer
            g2.setPaint(Color.BLACK);
            g2.setComposite(AlphaComposite.Clear);
            g2.fillRect(0, 0, effectBounds.width, effectBounds.height);

            if (debug) {
                g2.setPaint(Color.WHITE);
                g2.setComposite(AlphaComposite.SrcOver);
                g2.drawRect(0, 0, effectBounds.width - 1,
                        effectBounds.height - 1);
            }

            // turn on smoothing
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            g2.translate(getEffectWidth() - getOffset().getX(),
                    getEffectWidth() - getOffset().getY());
            paintBorderGlow(g2, clipShape, width, height);

            // clip out the parts we don't want
            g2.setComposite(AlphaComposite.Clear);
            g2.setColor(Color.WHITE);
            if (isRenderInsideShape()) {
                // clip the outside
                Area area = new Area(effectBounds);
                area.subtract(new Area(clipShape));
                g2.fill(area);
            } else {
                // clip the inside
                g2.fill(clipShape);
            }
        } finally {
            // draw the final image
            g2.dispose();
        }

        int drawX = (int) (-getEffectWidth() + getOffset().getX());
        int drawY = (int) (-getEffectWidth() + getOffset().getY());
        g.drawImage(clipImage, drawX, drawY, null);
    } else {
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        paintBorderGlow(g, clipShape, width, height);
    }

    //g.setColor(Color.MAGENTA);
    //g.draw(clipShape.getBounds2D());
    //g.drawRect(0,0,width,height);

    g.setComposite(savedComposite);
}
 
Example 20
Source File: TextureApng.java    From Custom-Main-Menu with MIT License 4 votes vote down vote up
private void load()
{
	frameTextureID = new HashMap<Frame, Integer>();
	try
	{
		InputStream inputStream = Minecraft.getMinecraft().getResourceManager().getResource(rl).getInputStream();

		Argb8888BitmapSequence pngContainer = Png.readArgb8888BitmapSequence(inputStream);
		animationControl = pngContainer.getAnimationControl();

		frames = Collections.synchronizedList(pngContainer.getAnimationFrames());

		BufferedImage canvas = new BufferedImage(pngContainer.defaultImage.width, pngContainer.defaultImage.height, BufferedImage.TYPE_INT_ARGB);
		Graphics2D graphics = canvas.createGraphics();
		graphics.setBackground(new Color(0, 0, 0, 0));

		BufferedImage frameBackup = new BufferedImage(pngContainer.defaultImage.width, pngContainer.defaultImage.height, BufferedImage.TYPE_INT_ARGB);
		Graphics2D graphicsBackup = frameBackup.createGraphics();
		graphicsBackup.setBackground(new Color(0, 0, 0, 0));

		for (int i = 0; i < frames.size(); i++)
		{
			Frame f = frames.get(i);

			switch (f.control.blendOp)
			{
				case 0:
					graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC));
					break;
				case 1:
					graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
					break;
			}

			Argb8888Bitmap bitmap = f.bitmap;

			BufferedImage buffered = new BufferedImage(bitmap.width, bitmap.height, BufferedImage.TYPE_INT_ARGB);
			buffered.setRGB(0, 0, bitmap.width, bitmap.height, bitmap.getPixelArray(), 0, bitmap.width);

			graphicsBackup.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
			graphicsBackup.drawImage(canvas, 0, 0, canvas.getWidth(), canvas.getHeight(), null);

			graphics.drawImage(buffered, f.control.xOffset, f.control.yOffset, f.control.xOffset + f.control.width, f.control.yOffset + f.control.height, 0, 0, buffered.getWidth(), buffered.getHeight(), null);

			frameTextureID.put(f, TextureUtil.uploadTextureImageAllocate(GL11.glGenTextures(), canvas, false, false));

			switch (f.control.disposeOp)
			{
				case 0:
					break;
				case 1:
					graphics.clearRect(f.control.xOffset, f.control.yOffset, f.control.width, f.control.height);
					break;
				case 2:
					graphics.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
					graphics.drawImage(frameBackup, 0, 0, canvas.getWidth(), canvas.getHeight(), null);
					break;
			}
		}
		
		graphics.dispose();
		graphicsBackup.dispose();
	}
	catch (Exception e)
	{
		e.printStackTrace();
		errored = true;
		return;
	}
	
	Frame frame = frames.get(0);

	float numerator = frame.control.delayNumerator;
	float denominator = frame.control.delayDenominator > 0 ? frame.control.delayDenominator : 100;

	this.currentFrameDelay = (int) (numerator / denominator * 1000);
	this.lastTimeStamp = System.currentTimeMillis();
}