Images

We're now going to look at creating images. The code library we use to create images is not built-in to Scala. You will need to add the following to the worksheet to be able to use it.

import cats.effect.unsafe.implicits.global
import doodle.core._
import doodle.image._
import doodle.syntax.all._
import doodle.image.syntax.all._
import doodle.java2d._

Let's start with some simple shapes, programming in the worksheet as we've done before.

Image.circle(10)
// res0: Image = Circle(d = 10.0)

What is happening here? Image is an object and circle a method on that object. We pass to circle a parameter, 10 that gives the diameter of the circle we're constructing. Note the type of the result: an Image.

Image.circle(10)
// res1: Image = Circle(d = 10.0)

We draw the circle by calling the draw method.

Image.circle(10).draw()

A window should appear as shown in Figure pictures:circle.

A circle

Doodle supports a handful of "primitive" images: circles, rectangles, and triangles. Let's try drawing a rectangle.

Image.rectangle(100, 50).draw()

The output is shown in Figure pictures:rectangle.

A rectangle

Finally let's try a triangle, for which the output is shown in Figure pictures:triangle.

Image.triangle(60, 40).draw()

A triangle

Exercises

I Go Round in Circles

Create circles that are 1, 10, and 100 units wide. Now draw them!

In this exercise we're checking that our Doodle install is working correctly and we're getting used to using the library. One of the important points in Doodle is we separate defining the image from drawing the image. We'll talk more about this throughout the book.

We can create circles with the code below.

Image.circle(1)
Image.circle(10)
Image.circle(100)

We can draw the circles by calling the draw method on each circle.

Image.circle(1).draw()
Image.circle(10).draw()
Image.circle(100).draw()

My Type of Art

What is the type of a circle? A rectangle? A triangle?

They all have type Image, as we can tell from the console.

:type Image.circle(10)
// doodle.core.Image
:type Image.rectangle(10, 10)
// doodle.core.Image
:type Image.triangle(10, 10)
// doodle.core.Image

Not My Type of Art

What's the type of drawing an image? What does this mean?

Once again, we can ask the console this quesstion.

:type Image.circle(10).draw()
// Unit

We see that the type of drawing an image is Unit. Unit is the type of expressions that have no interesting value to return. This is the case for draw; we call it because we want something to appear on the screen, not because we have a use for the value it returns. There is only one value with type Unit. This value is also called unit, which written as a literal expression is ()

You'll note that the console doesn't print unit by default.

()

We can ask the console for the type to show that there really is unit here.

:type ()
// Unit