Java Code Examples for java.awt.Graphics.dispose()

The following are Jave code examples for showing how to use dispose() of the java.awt.Graphics class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Logisim   File: ComponentIcon.java   View Source Code Vote up 7 votes
@Override
public void paintIcon(java.awt.Component c, Graphics g, int x, int y) {
	// draw tool icon
	Graphics gIcon = g.create();
	ComponentDrawContext context = new ComponentDrawContext(c, null, null, g, gIcon);
	comp.getFactory().paintIcon(context, x, y, comp.getAttributeSet());
	gIcon.dispose();

	if (triangleState != TRIANGLE_NONE) {
		int[] xp;
		int[] yp;
		if (triangleState == TRIANGLE_CLOSED) {
			xp = new int[] { x + 13, x + 13, x + 17 };
			yp = new int[] { y + 11, y + 19, y + 15 };
		} else {
			xp = new int[] { x + 11, x + 19, x + 15 };
			yp = new int[] { y + 13, y + 13, y + 17 };
		}
		g.setColor(Color.LIGHT_GRAY);
		g.fillPolygon(xp, yp, 3);
		g.setColor(Color.DARK_GRAY);
		g.drawPolygon(xp, yp, 3);
	}
}
 
Example 2
Project: openjdk-jdk10   File: CGLGraphicsConfig.java   View Source Code Vote up 6 votes
@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
Project: sumo   File: MaskGeometries.java   View Source Code Vote up 6 votes
/**
 * rasterize the mask clipped with the Rectangle scaled back to full size with an offset onto a BufferedImage
 */
public BufferedImage rasterize(Rectangle rect, int offsetX, int offsetY, double scalingFactor) {

	// create the buffered image of the size of the Rectangle
    BufferedImage image = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_BYTE_BINARY);
    GeometryFactory gf = new GeometryFactory();

    // define the clipping region in full scale
    Coordinate[] coords = new Coordinate[]{
        new Coordinate((int) (((double) rect.getMinX() / scalingFactor)), (int) (((double) rect.getMinY() / scalingFactor))),
        new Coordinate((int) (((double) rect.getMaxX() / scalingFactor)), (int) (((double) rect.getMinY() / scalingFactor))),
        new Coordinate((int) (((double) rect.getMaxX() / scalingFactor)), (int) (((double) rect.getMaxY() / scalingFactor))),
        new Coordinate((int) (((double) rect.getMinX() / scalingFactor)), (int) (((double) rect.getMaxY() / scalingFactor))),
        new Coordinate((int) (((double) rect.getMinX() / scalingFactor)), (int) (((double) rect.getMinY() / scalingFactor))),};

    Polygon geom = gf.createPolygon(gf.createLinearRing(coords));

    Graphics g2d = image.getGraphics();

    g2d.setColor(Color.white);
    for (Geometry p : maskGeometries) {
    	/*if(p instanceof MultiPolygon){
    		p=p.getBoundary();
    	}*/
        if (p.intersects(geom)) {
            int[] xPoints = new int[p.getNumPoints()];//build array for x coordinates
            int[] yPoints = new int[p.getNumPoints()];//build array for y coordinates
            int i = 0;
            for (Coordinate c : p.getCoordinates()) {
                xPoints[i] = (int) ((c.x + offsetX ) * scalingFactor);
                yPoints[i] = (int) ((c.y + offsetY ) * scalingFactor);
                i++;
            }
            g2d.fillPolygon(xPoints, yPoints, i);
        }
    }
    g2d.dispose();
    return image;

}
 
Example 4
Project: Logisim   File: CircuitAppearance.java   View Source Code Vote up 6 votes
public void paintSubcircuit(Graphics g, Direction facing) {
	Direction defaultFacing = getFacing();
	double rotate = 0.0;
	if (facing != defaultFacing && g instanceof Graphics2D) {
		rotate = defaultFacing.toRadians() - facing.toRadians();
		((Graphics2D) g).rotate(rotate);
	}
	Location offset = findAnchorLocation();
	g.translate(-offset.getX(), -offset.getY());
	for (CanvasObject shape : getObjectsFromBottom()) {
		if (!(shape instanceof AppearanceElement)) {
			Graphics dup = g.create();
			shape.paint(dup, null);
			dup.dispose();
		}
	}
	g.translate(offset.getX(), offset.getY());
	if (rotate != 0.0) {
		((Graphics2D) g).rotate(-rotate);
	}
}
 
Example 5
Project: myfaces-trinidad   File: OffscreenWrappingPainter.java   View Source Code Vote up 6 votes
@Override
public Dimension getPreferredSize(PaintContext context)
{
  Dimension size = null;

  // Get a shared buffer to use for measuring
  BufferedImage buffer = _createOffscreenBuffer(context, 1, 1);

  if (buffer != null)
  {
    Graphics g = _getInitializedGraphics(context, buffer);
    size = super.getPreferredSize(new ProxyContext(context, g));

    // Clean up
    g.dispose();
    buffer.flush();
  }
  else
  {
    // If we didn't get a buffer, just paint the contents directly
    size = super.getPreferredSize(context);
  }

  return size;
}
 
Example 6
Project: incubator-netbeans   File: ToggleButtonMenuItem.java   View Source Code Vote up 6 votes
private static Icon createMenuIcon(Icon icon, Component decorator) {
    int h = menuIconSize();
    int w = UIUtils.isAquaLookAndFeel() ? h + 4 : h;

    BufferedImage i = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics g = i.getGraphics();

    if (decorator != null) {
        decorator.setSize(w, h);
        decorator.paint(g);
    }

    icon.paintIcon(null, g, (w - icon.getIconWidth()) / 2, (h - icon.getIconHeight()) / 2);
    g.dispose();

    return new ImageIcon(i);
}
 
Example 7
Project: openjdk-jdk10   File: TestEnvironment.java   View Source Code Vote up 5 votes
public void erase() {
    Graphics g = getGraphics();
    if (g != null) {
        g.setColor(Color.white);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.dispose();
    }
}
 
Example 8
Project: awe-awesomesky   File: CodeUtil.java   View Source Code Vote up 5 votes
private static void insertImage(BufferedImage source, String imgPath,
        boolean needCompress) throws Exception {
    File file = new File(imgPath);
    if (!file.exists()) {
        System.err.println(""+imgPath+"   该文件不存在!");
        return;
    }
    Image src = ImageIO.read(new File(imgPath));
    int width = src.getWidth(null);
    int height = src.getHeight(null);
    if (needCompress) {// 压缩LOGO
        if (width > WIDTH) {
            width = WIDTH;
        }
        if (height > HEIGHT) {
            height = HEIGHT;
        }
        Image image = src.getScaledInstance(width, height,
                Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.drawImage(image, 0, 0, null); // 绘制缩小后的图
        g.dispose();
        src = image;
    }
 // 插入LOGO
    Graphics2D graph = source.createGraphics();
    int x = (QRCODE_SIZE - width) / 2;
    int y = (QRCODE_SIZE - height) / 2;
    graph.drawImage(src, x, y, width, height, null);
    Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
    graph.setStroke(new BasicStroke(3f));
    graph.draw(shape);
    graph.dispose();
}
 
Example 9
Project: The-Mysterious-Mind-Of-Jack   File: GameCanvas.java   View Source Code Vote up 5 votes
public void draw() {
	requestFocus();
       BufferStrategy bs = getBufferStrategy();
       if (bs == null) {
           createBufferStrategy(3);
           return;
       }

       Graphics g = currentFrame.getGraphics();
       GameCanvas.g = g;
       g.setColor(Color.GRAY);
       g.fillRect(0, 0, getWidth(), getHeight());
       
       if (Game.paused) {
       	if (!isBlurred) {
        	if (StateHandler.pausedGame != null) {
	        	StateHandler.pausedGame.render(g);
	        	blurred = Tools.blur(currentFrame);
	        	isBlurred = true;
        	}
       	}
       } else isBlurred = false;
       
       StateHandler.render(g);
       
       bs.getDrawGraphics().drawImage(currentFrame, 0, 0, StateHandler.WIDTH, StateHandler.HEIGHT, null);
       
       g.dispose();
       bs.show();
}
 
Example 10
Project: openjdk-jdk10   File: bug8032667_image_diff.java   View Source Code Vote up 5 votes
static BufferedImage getImage(JComponent component, int scale, int width, int height) {
    final BufferedImage image = new BufferedImage(
            scale * width, scale * height, BufferedImage.TYPE_INT_ARGB);
    final Graphics g = image.getGraphics();
    ((Graphics2D) g).scale(scale, scale);
    component.paint(g);
    g.dispose();
    return image;
}
 
Example 11
Project: Logisim   File: Drawing.java   View Source Code Vote up 5 votes
@Override
public void paint(Graphics g, Selection selection) {
	Set<CanvasObject> suppressed = selection.getDrawsSuppressed();
	for (CanvasObject shape : getObjectsFromBottom()) {
		Graphics dup = g.create();
		if (suppressed.contains(shape)) {
			selection.drawSuppressed(dup, shape);
		} else {
			shape.paint(dup, null);
		}
		dup.dispose();
	}
}
 
Example 12
Project: openjdk-jdk10   File: MultiResolutionDrawImageWithTransformTest.java   View Source Code Vote up 5 votes
public TestSurfaceData(int width, int height, double scale) {
    super(StateTrackable.State.DYNAMIC, SurfaceType.Custom, ColorModel.getRGBdefault());
    this.scale = scale;
    gc = new TestGraphicsConfig(scale);
    this.width = (int) Math.ceil(scale * width);
    this.height = (int) Math.ceil(scale * height);
    buffImage = new BufferedImage(this.width, this.height,
            BufferedImage.TYPE_INT_RGB);

    Graphics imageGraphics = buffImage.createGraphics();
    imageGraphics.setColor(BACKGROUND_COLOR);
    imageGraphics.fillRect(0, 0, this.width, this.height);
    imageGraphics.dispose();
}
 
Example 13
Project: Logisim   File: LayoutToolbarModel.java   View Source Code Vote up 5 votes
@Override
public void paintIcon(Component destination, Graphics g) {
	// draw halo
	if (tool == haloedTool && AppPreferences.ATTRIBUTE_HALO.getBoolean()) {
		g.setColor(Canvas.HALO_COLOR);
		g.fillRect(1, 1, 22, 22);
	}

	// draw tool icon
	g.setColor(Color.BLACK);
	Graphics g_copy = g.create();
	ComponentDrawContext c = new ComponentDrawContext(destination, null, null, g, g_copy);
	tool.paintIcon(c, 2, 2);
	g_copy.dispose();
}
 
Example 14
Project: betaexpansion   File: TextureWatchFX.java   View Source Code Vote up 5 votes
public TextureWatchFX(Minecraft minecraft)
{
    super(Item.pocketSundial.getIconFromDamage(0));
    isCustom = true;
    mc = minecraft;
    res = (Integer)mc.renderEngine.textureSizeIdMap.get(mc.renderEngine.getTexture("/gui/items.png"))/16;
    watchIconImageData = new int[res*res];
    dialImageData = new int[res*res];
    imageData = new byte[res*res*4];
    tileImage = 1;
    try
    {
        BufferedImage bufferedimage = ImageIO.read(mc.texturePackList.selectedTexturePack.getResourceAsStream("/gui/items.png"));
        int i = (iconIndex % 16) * res;
        int j = (iconIndex / 16) * res;
        bufferedimage.getRGB(i, j, res, res, watchIconImageData, 0, res);
        bufferedimage = ImageIO.read(mc.texturePackList.selectedTexturePack.getResourceAsStream("/misc/dial.png"));
        if(bufferedimage.getWidth() != res)
        {
        	BufferedImage tmp = new BufferedImage(res,res,BufferedImage.TYPE_4BYTE_ABGR);
        	Graphics g = tmp.createGraphics();
        	g.drawImage(bufferedimage, 0, 0, res,res, null);
        	g.dispose();
        	bufferedimage = tmp;
        }
        bufferedimage.getRGB(0, 0, res, res, dialImageData, 0, res);
    }
    catch(IOException ioexception)
    {
        ioexception.printStackTrace();
    }
}
 
Example 15
Project: jdk8u-jdk   File: BufferStrategyExceptionTest.java   View Source Code Vote up 5 votes
public void render() {
    ImageCapabilities imgBackBufCap = new ImageCapabilities(true);
    ImageCapabilities imgFrontBufCap = new ImageCapabilities(true);
    BufferCapabilities bufCap =
        new BufferCapabilities(imgFrontBufCap,
            imgBackBufCap, BufferCapabilities.FlipContents.COPIED);
    try {

        createBufferStrategy(2, bufCap);
    } catch (AWTException ex) {
        createBufferStrategy(2);
    }

    BufferStrategy bs = getBufferStrategy();
    do {
        Graphics g =  bs.getDrawGraphics();
        g.setColor(Color.green);
        g.fillRect(0, 0, getWidth(), getHeight());

        g.setColor(Color.red);
        g.drawString("Rendering test", 20, 20);

        g.drawImage(bi, 50, 50, null);

        g.dispose();
        bs.show();
    } while (bs.contentsLost()||bs.contentsRestored());
}
 
Example 16
Project: openjdk-jdk10   File: MatteBorder.java   View Source Code Vote up 5 votes
private void paintEdge(Component c, Graphics g, int x, int y, int width, int height, int tileW, int tileH) {
    g = g.create(x, y, width, height);
    int sY = -(y % tileH);
    for (x = -(x % tileW); x < width; x += tileW) {
        for (y = sY; y < height; y += tileH) {
            this.tileIcon.paintIcon(c, g, x, y);
        }
    }
    g.dispose();
}
 
Example 17
Project: Yidu   File: SecurityImage.java   View Source Code Vote up 4 votes
/**
 * 生成验证码图片
 * 
 * @param securityCode
 *            验证码字符
 * @return BufferedImage 图片
 */
public static BufferedImage createImage(String securityCode) {
    // 验证码长度
    int codeLength = securityCode.length();
    // 字体大小
    int fSize = 15;
    int fWidth = fSize + 1;
    // 图片宽度
    int width = codeLength * fWidth + 6;
    // 图片高度
    int height = fSize * 2 + 1;
    // 图片
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.createGraphics();
    // 设置背景色
    g.setColor(Color.WHITE);
    // 填充背景
    g.fillRect(0, 0, width, height);
    // 设置边框颜色
    g.setColor(Color.LIGHT_GRAY);
    // 边框字体样式
    g.setFont(new Font("Arial", Font.BOLD, height - 2));
    // 绘制边框
    g.drawRect(0, 0, width - 1, height - 1);
    // 绘制噪点
    Random rand = new Random();
    // 设置噪点颜色
    g.setColor(Color.LIGHT_GRAY);
    for (int i = 0; i < codeLength * 6; i++) {
        int x = rand.nextInt(width);
        int y = rand.nextInt(height);
        // 绘制1*1大小的矩形
        g.drawRect(x, y, 1, 1);
    }
    // 绘制验证码
    int codeY = height - 10;
    // 设置字体颜色和样式
    g.setColor(new Color(19, 148, 246));
    g.setFont(new Font("Georgia", Font.BOLD, fSize));
    for (int i = 0; i < codeLength; i++) {
        g.drawString(String.valueOf(securityCode.charAt(i)), i * 16 + 5, codeY);
    }
    // 关闭资源
    g.dispose();
    return image;
}
 
Example 18
Project: OpenJSharp   File: InputImageTests.java   View Source Code Vote up 4 votes
Context(TestEnvironment env, Result result, int testType) {
    super(env, result);

    String content = (String)env.getModifier(contentList);
    if (content == null) {
        content = CONTENT_BLANK;
    }
    // REMIND: add option for non-opaque images
    image = createBufferedImage(size, size, content, false);

    result.setUnits(size*size);
    result.setUnitName("pixel");

    if (testType == TEST_IMAGEIO || testType == TEST_IMAGEREADER) {
        ImageReaderSpi readerspi =
            (ImageReaderSpi)env.getModifier(imageioReadFormatList);
        format = readerspi.getFileSuffixes()[0].toLowerCase();
        if (testType == TEST_IMAGEREADER) {
            seekForwardOnly = env.isEnabled(seekForwardOnlyTog);
            ignoreMetadata = env.isEnabled(ignoreMetadataTog);
            try {
                reader = readerspi.createReaderInstance();
            } catch (IOException e) {
                System.err.println("error creating reader");
                e.printStackTrace();
            }
            if (env.isEnabled(installListenerTog)) {
                reader.addIIOReadProgressListener(
                    new ReadProgressListener());
            }
        }
        if (format.equals("wbmp")) {
            // REMIND: this is a hack to create an image that the
            //         WBMPImageWriter can handle (a better approach
            //         would involve checking the ImageTypeSpecifier
            //         of the writer's default image param)
            BufferedImage newimg =
                new BufferedImage(size, size,
                                  BufferedImage.TYPE_BYTE_BINARY);
            Graphics g = newimg.createGraphics();
            g.drawImage(image, 0, 0, null);
            g.dispose();
            image = newimg;
        }
    } else if (testType == TEST_TOOLKIT) {
        format = (String)env.getModifier(toolkitReadFormatList);
    } else { // testType == TEST_JPEGCODEC
        format = "jpeg";
    }

    initInput();
}
 
Example 19
Project: util4j   File: ChangeImageSize.java   View Source Code Vote up 4 votes
/**  
 * 图像切割    
 * @param srcImageFile 源图像地址    
 * @param descDir      切片目标文件夹    
 * @param destWidth    目标切片宽度    
 * @param destHeight   目标切片高度    
 */     
public static void cut(String srcImageFile, String descDir, int destWidth, int destHeight)      
{      
    try     
    {      
        Image img;      
        ImageFilter cropFilter;    
        String dir = null;   
        // 读取源图像      
        BufferedImage bi = ImageIO.read(new File(srcImageFile));      
        int srcWidth = bi.getHeight(); // 源图宽度      
        int srcHeight = bi.getWidth(); // 源图高度   
        System.out.println("srcWidth:"+srcWidth);   
        System.out.println("srcHeight:"+srcHeight);   
        if (srcWidth > destWidth && srcHeight > destHeight)      
        {      
            Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);      
            destWidth = 300; // 切片宽度      
            destHeight = 300; // 切片高度      
            int cols = 0; // 切片横向数量      
            int rows = 0; // 切片纵向数量      
            // 计算切片的横向和纵向数量      
            if (srcWidth % destWidth == 0)      
            {      
                cols = srcWidth / destWidth;      
            }      
            else     
            {      
                cols = (int) Math.floor(srcWidth / destWidth) + 1;      
            }      
            if (srcHeight % destHeight == 0)      
            {      
                rows = srcHeight / destHeight;      
            }      
            else     
            {      
                rows = (int) Math.floor(srcHeight / destHeight) + 1;      
            }      
            // 循环建立切片                  
            for (int i = 0; i < rows; i++)      
            {      
                for (int j = 0; j < cols; j++)      
                {      
                    // 四个参数分别为图像起点坐标和宽高      
                    // 即: CropImageFilter(int x,int y,int width,int height)      
                    cropFilter = new CropImageFilter(j * 300, i * 300, destWidth, destHeight);      
                    img = Toolkit.getDefaultToolkit().createImage(      
                                    new FilteredImageSource(image.getSource(), cropFilter));      
                    BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);      
                    Graphics g = tag.getGraphics();      
                    g.drawImage(img, 0, 0, null); // 绘制缩小后的图      
                    g.dispose();      
                    // 输出为文件     
                    dir = descDir + "cut_image_" + i + "_" + j + ".jpg";   
                    File f = new File(dir);   
                    ImageIO.write(tag, "JPEG",f);   
                    System.out.println(dir);   
                   // ImageUtils.pressText("水印",dir,"宋体",1,1,25,10,10);   
                }      
            }      
        }      
    }      
    catch (Exception e)      
    {      
        e.printStackTrace();      
    }      
}
 
Example 20
Project: jdk8u-jdk   File: RSLAPITest.java   View Source Code Vote up 4 votes
private static void testVICreation(AccelGraphicsConfig agc, int cap,
                                   int transparency, int type)
{
    int caps = agc.getContextCapabilities().getCaps();
    int w = 11, h = 17;

    VolatileImage vi =
        agc.createCompatibleVolatileImage(w, h, transparency, type);
    if ((cap & caps) != 0) {
        if (vi == null) {
            System.out.printf("Failed: cap=%d is supported but " +
                              "image wasn't created\n", cap);
            throw new RuntimeException("Failed: image wasn't created " +
                                       "for supported cap");
        } else {
            if (!(vi instanceof DestSurfaceProvider)) {
                throw new RuntimeException("Failed: created VI is not " +
                                           "DestSurfaceProvider");
            }
            Surface s = ((DestSurfaceProvider) vi).getDestSurface();
            if (s instanceof AccelSurface) {
                AccelSurface as = (AccelSurface) s;
                printSurface(as);
                if (as.getType() != type) {
                    throw new RuntimeException("Failed: returned VI is" +
                            " of incorrect type: " + as.getType() +
                            " requested type=" + type);
                } else {
                    System.out.printf("Passed: VI of type %d was " +
                            "created for cap=%d\n", type, cap);
                }
                if (as.getType() == TEXTURE) {
                    boolean ex = false;
                    try {
                        Graphics g = vi.getGraphics();
                        g.dispose();
                    } catch (UnsupportedOperationException e) {
                        ex = true;
                    }
                    if (!ex) {
                        throw new RuntimeException("Failed: " +
                            "texture.getGraphics() didn't throw exception");
                    } else {
                        System.out.println("Passed: VI.getGraphics()" +
                                " threw exception for texture-based VI");
                    }
                }
            } else {
                System.out.printf("Passed: VI of type %d was " +
                        "created for cap=%d but accel surface is null\n",
                        type, cap);
            }
        }
    } else {
        if (vi != null) {
            throw new RuntimeException("Failed: created VI for " +
                                       "unsupported cap=" + cap);
        }
    }
}