awt

Set a clipping area from a Shape example

In this example we shall show you how to set a clipping area from a component, in this case an image. This is a very basic operations that you will need when you are working in Java desktop applications that have rich graphcis.

Basically all you have to do in order to set a clipping aread from a shape is:

  • Use Toolkit.getDefaultToolkit().getImage(String imageURL) to load an image. Or you can just use the built int functions to create simple shape.
  • Create a class that extends component
  • Use java.awt.geom.Ellipse2D.Float to set up a simple ellipse shape.
  • Use Graphics2D.setClip to set the above ellipse as the clipping area.

Let’s see the code:

package com.javacodegeeks.snippets.desktop;

import java.awt.Component;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.Toolkit;

public class ShapeClipping {

  static Image image;

  public static void main(String[] args) {

// The image URL - change to where your image file is located!

String imageURL = "image.png";

// This call returns immediately and pixels are loaded in the background

image = Toolkit.getDefaultToolkit().getImage(imageURL);

// Create a frame

Frame frame = new Frame();

// Add a component with a custom paint method

frame.add(new CustomPaintComponent());

// Display the frame

int frameWidth = 300;

int frameHeight = 300;

frame.setSize(frameWidth, frameHeight);

frame.setVisible(true);

  }

  /*
    * To draw on the screen, it is first necessary to subclass a Component and
    * override its paint() method. The paint() method is automatically called
    * by the windowing system whenever component's area needs to be repainted.
    */
  static class CustomPaintComponent extends Component {

public void paint(Graphics g) {

    // Retrieve the graphics context; this object is used to paint

    // shapes

    Graphics2D g2d = (Graphics2D) g;

    // Create an oval shape that's as large as the component

    int x = 0;

    int y = 0;

    int width = getSize().width - 1;

    int height = getSize().height - 1;

    Shape shape = new java.awt.geom.Ellipse2D.Float(x, y, width, height);

    // Set the clipping area

    g2d.setClip(shape);

    // Draw an image

    g2d.drawImage(image, x, y, this);

}

  }

}

 
This was an example on how to set a clipping area from a Shape.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button