Recursive graphics --java

In real life, we often see some very regular graphics, such as the following:

How to draw it in java language?

Here we will use recursive thinking, which is used in the commonly used Fibonacci sequence.

When there are many things and they have the same law, we can use recursion to push from the former to the latter.

At this point, you only need to enter the initial conditions to complete a complicated thing.

Methods as below:

Think about the underlying laws,

We can think of it as drawing a solid rectangle in the center, and then draw a small solid rectangle around it, and then consider the small rectangle as the center, and repeat the steps until the accuracy is required.

1. Draw a solid rectangle in the center (by default you have set the point coordinates, width and height parameters).

g.fillRect(x + w / 3, y + h / 3, w / 3, h / 3);

2. At this time, use recursion (recursion is reflected in "class-method" as calling itself), and draw small rectangles around it.

 drawrect(g, x + w / 3, y, w / 3, h / 3);

Only one is posted here as an example.

3. Set the recursion end condition (it is important to note that once the recursion is used, one must be alert to "dead recursion", that is, the loop continues and cannot be stopped)

There are two commonly used here:

A: Limit the number of times.

B: Limit the parameter range.

if (w > 10){
    前方的代码;
}

What is used here is to limit the parameter range.

And with that, we're done.

So if what we want to draw is this:

The idea is roughly the same, you can try it yourself.

What needs to be added is that we can use the Polygon class to draw triangles.

            Polygon plo=new Polygon();
            plo.addPoint((a1+a2)/2,(b1+b2)/2);
            plo.addPoint((a2+a3)/2,(b2+b3)/2);
            plo.addPoint((a1+a3)/2,(b1+b3)/2);
            g.fillPolygon(plo);

We often see the line chart of the stock market, the ups and downs of mountains,

The idea is the same, but the connection only needs to be started when the last call is made.

Analogously, only draw the smallest rectangle, triangle.

We can also upgrade it a little bit and add random colors to them. These are all mentioned before, so I won’t go into details.

Guess you like

Origin blog.csdn.net/AkinanCZ/article/details/125221634