cmptUser
cmptUser

Reputation: 51

Drawing a circle on a bufferedImage in Java

I want to draw a circle on a buffered image that act like a png

i want to use this circle in order to replace the mouse cursor for a paint application i am working on.

i cant download a circle png from google as i need to keep changing the size of this circle depending on the width of the tool i am using it for.

here is my attempt so far

  public static BufferedImage getCircle() {

    BufferedImage bufferedImage = new BufferedImage(30, 30, BufferedImage.TYPE_INT_RGB);
    Color transparent = new Color(0x00FFFFFF, true);

    Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
    //trying to make the bufferedImage transparent 
    g.setComposite(AlphaComposite.Src);
    g.setColor(transparent);
    g.setBackground(transparent);
    g.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());
    //drawing the circle 
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.setColor(Color.black);
    g.drawOval(0, 0, 200, 200);
    return bufferedImage;
}

it should look like:

enter image description here

However my code currently only creates a white square.

Upvotes: 2

Views: 4320

Answers (1)

Zabuzard
Zabuzard

Reputation: 25943

Your code has two problems (as already shown in the comments). The first is that you draw a circle with a radius of 200px into an image of dimensions 30px. If you closely look you can barely see a black pixel in the lower right corner.

Fix it by adjusting your dimensions such that it fits inside, for example like:

BufferedImage bufferedImage = new BufferedImage(60, 60, BufferedImage.TYPE_INT_RGB);
...
g.drawOval(5, 5, 50, 50);

Next is that you want to achieve a transparent background. To do so you need to set the type of the image to a color model which supports transparency, like ARGB (A = Alpha = transparency) instead of RGB:

BufferedImage bufferedImage = new BufferedImage(60, 60, BufferedImage.TYPE_INT_ARGB);

Last you probably want to increase the thickness of your border to achieve the image you showed. You do so by using g.setStroke(...):

g.setColor(Color.BLACK);
g.setStroke(new BasicStroke(5));
g.drawOval(5, 5, 50, 50);

With this setting you achieve the following result (with transparency):

resulting circle

Play with the values to adjust the circle to your exact needs.

Upvotes: 3

Related Questions