I am having some serious troubles implementing a draw in the scala language. my current code looks like:
package edu.luc.cs.laufer.cs473.shapealgebra
import java.awt.Graphics2D
class Draw {
def draw(g: Graphics2D)(s: Shape): Unit = s match {
case Ellipse(hw, hh) => g.drawArc(-hw, -hh, 2 * hw, 2 * hh, 0, 360)
case Rectangle(w, h) => g.drawRect(0, 0, w, h)
case Location(x: Int, y: Int, shape: Shape) => {
g.translate(x, y)
draw(g)(shape)
g.translate(0,0)
}
case Group(shapes @ _*) => {
shapes foreach(draw(g)(_))
}
}
}
object Draw extends Draw {
def apply(g: Graphics2D) = draw(g)(_)
}
The problem here is with my group case. It does not draw a group of shapes properly. The two test cases uses the following shapes:
val simpleLocation = Location(70, 30, Rectangle(80, 120))
val complexGroup = Location(50, 100,
Group(
Ellipse(20, 20),
Location(150, 50,
Group(
Rectangle(50, 30),
Rectangle(300, 60),
Location(100, 200,
Ellipse(50, 50)
)
)
),
Rectangle(100, 200)
)
)
The complex continues to fail and I can’t figure out why.
package edu.luc.cs.laufer.cs473.shapealgebra
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FunSuite
import java.awt.image.BufferedImage
import TestFixtures._
@RunWith(classOf[JUnitRunner])
class TestDraw extends FunSuite with BufferedImageEquality {
test("simple") {
val s = simpleLocation
val i = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB)
Draw(i.createGraphics())(s)
val j = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB)
val g = j.createGraphics()
g.translate(70, 30)
g.drawRect(0, 0, 80, 120)
assertEquals(i, j)
}
test("complex") {
val s = complexGroup
val i = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB)
Draw(i.createGraphics())(s)
val j = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB)
val g = j.createGraphics()
paintComplexGroup(g)
assertEquals(i, j)
}
}
The test case is shown above. I get a “0 did not equal 255” from the result of the unit test.
If you look at what
translatedoes, the Javadoc saysSo
does nothing. Try
Although, if it were me, I wouldn’t mess with the Graphics object’s origin. I’d modify the
drawRectanddrawArcstatements to take a location, and pass the location co-ordiates as an argument to the method.