Java code example: drawing a heart-shaped pattern
import javax.swing.*; import java.awt.*; public class HeartPattern extends JFrame { public HeartPattern() { setTitle("Heart Pattern"); setSize(500, 500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.RED); g2d.setStroke(new BasicStroke(3)); int x = getWidth() / 2; int y = getHeight() / 2; int radius = 100; // 绘制左半部分的心形 for (int i = -radius; i <= 0; i++) { double y1 = Math.sqrt(radius * radius - i * i); g2d.drawLine(x + i, y - (int) y1, x + i, y + (int) y1); } // 绘制右半部分的心形 for (int i = radius; i >= 0; i--) { double y1 = Math.sqrt(radius * radius - i * i); g2d.drawLine(x + i, y - (int) y1, x + i, y + (int) y1); } } public static void main(String[] args) { HeartPattern hp = new HeartPattern(); hp.setVisible(true); } }
This is a simple Java program that inherits the JFrame class and implements overriding the paint method to draw a heart shape pattern. The size of the form is set in the code, and the form is drawn by calling super.paint(g)
, and then the Graphics2D
object g2d is used to draw the heart shape, and the color of the brush is set to Red, brush thickness is 3 pixels. Next, the abscissa x and ordinate y of the pattern center point are defined, and the radius of the heart-shaped drawing is set to 100. Then use a for loop to draw the left half of the heart, and the right half of the heart. Finally, create the HeartPattern object in the main method and set the form to be visible. After running the program, a form with a heart-shaped pattern will appear.
The above is the detailed content of Write a function that generates heart-shaped patterns in Java language. For more information, please follow other related articles on the PHP Chinese website!