0

How to draw heart using java awt library? I am using Java AWT library and I need to draw a heart for my game. How can I do this using AWT?

Here what I was thinking: may be use g.fillArc()? but then if I make two curves at top than how to make a triangle at button? Would that be g.fillPolygon()?

g.fillArc(x, y, 20,20, 60, 60); //so this will be left curve

g.fillArc(x+20, y, 20,20, 60, 60); //so right curve?

//button triangle?

I was wondering if any one is experence in awt and could show me how to do this?

2 Answers 2

2

Had to write this code for something I'm doing and it works well enough. Draws a triangle at x and y with the specified width and height using graphics g.

// Draw a heart.
public void drawHeart(Graphics g, int x, int y, int width, int height) {
    int[] triangleX = {
            x - 2*width/18,
            x + width + 2*width/18,
            (x - 2*width/18 + x + width + 2*width/18)/2};
    int[] triangleY = { 
            y + height - 2*height/3, 
            y + height - 2*height/3, 
            y + height };
    g.fillOval(
            x - width/12,
            y, 
            width/2 + width/6, 
            height/2); 
    g.fillOval(
            x + width/2 - width/12,
            y,
            width/2 + width/6,
            height/2);
    g.fillPolygon(triangleX, triangleY, triangleX.length);
}
1

//You don't really need AWT in Heart drawing here ://

public static void main(String[] args) {
       int H=7,W=7;
       for(int i=2;i<=(H+1)/2;i++){

      for(int j=0;j<W/2-i;j++){
        System.out.print(" ");
       }
    for(int k=1;k<(i+1)*2+1;k++){
    System.out.print("*");
    }

    if(i==2){
    System.out.print(" ");
    }

    for(int j=0;j<W/2-i+1;j++){
    System.out.print(" ");
    }

    for(int k=1;k<(i+1)*2+1;k++){
    if(i==(H+1)/2&&k>i+3)
    System.out.print("");
    else
    System.out.print("*");
    }
    System.out.println();

    }
    int HH=17,WW=17;
    for(int i=1;i<=HH/2;i++){

    for(int j=1;j<=i;j++){
    System.out.print(" ");
    }
    int z=WW-2*i;
    for(int k=1;k<=z;k++){
    System.out.print("*");
    }
    System.out.println();
 }
}

}

1
  • 1
    Nice text implementation, but it seems like since the author of the question was trying to use the shape in his game which uses AWT, drawing it in AWT would be necessary. Nov 26, 2016 at 20:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.