Java Tile Based Game Performance - java

I am currently in the process of experimenting with a 2D tile based side scrolling game in Java, primarily based on the code and examples from "Developing Games in Java" by David Brackeen
At the moment the map files are 100x100 tiles in size (each tile is 64x64 pixels). I have already configured the system to only display the tiles which are visible to the player. The Graphics system is managed by a ScreenManager class that returns the graphics object of the current BufferStrategy as follows:
ScreenManager.java
private GraphicsDevice device;
...
/**
* Gets the graphics context for the display. The
* ScreenManager uses double buffering, so applications must
* call update() to show any graphics drawn.
* <p>
* The application must dispose of the graphics object.
*/
public Graphics2D getGraphics(){
Window window = device.getFullScreenWindow();
if(window != null){
BufferStrategy strategy = window.getBufferStrategy();
return (Graphics2D)strategy.getDrawGraphics();
}
else{
return null;
}
}
After the graphics from this ScreenManager is passed along in the game loop to the draw method of the TreeRenderer.
TreeMapRenderer.java
/**
Draws the specified TileMap.
*/
public void draw(Graphics2D g, TileMap map,
int screenWidth, int screenHeight, float fr)
{
Sprite player = map.getPlayer();
int mapWidth = tilesToPixels(map.getWidth());
int mapHeight = tilesToPixels(map.getHeight());
// get the scrolling position of the map
// based on player's position
int offsetX = screenWidth / 2 -
Math.round(player.getX()) - TILE_SIZE;
offsetX = Math.min(offsetX, 0);
offsetX = Math.max(offsetX, screenWidth - mapWidth);
// get the y offset to draw all sprites and tiles
int offsetY = screenHeight /2 -
Math.round(player.getY()) - TILE_SIZE;
offsetY = Math.min(offsetY,0);
offsetY = Math.max(offsetY, screenHeight - mapHeight);
// draw the visible tiles
int firstTileY = pixelsToTiles(-offsetY);
int lastTileY = firstTileY + pixelsToTiles(screenHeight) +1;
int firstTileX = pixelsToTiles(-offsetX);
int lastTileX = firstTileX +
pixelsToTiles(screenWidth) + 1;
//HERE IS WHERE THE SYSTEM BOGS dOWN (checking ~280 tiles per iteration)
for (int y=firstTileY; y<lastTileY; y++) {
for (int x=firstTileX; x <= lastTileX; x++) {
if(map.getTile(x, y) != null){
Image image = map.getTile(x, y).getImage();
if (image != null) {
g.drawImage(image,
tilesToPixels(x) + offsetX,
tilesToPixels(y) + offsetY,
null);
}
}
}
}
// draw player
g.drawImage(player.getImage(),
Math.round(player.getX()) + offsetX,
Math.round(player.getY()) + offsetY,
null);
The algorithm works correctly selecting the correct FROM and TO values for the X and Y axis culling the needed tiles from 10000 to ~285.
My problem is that even with this the game will only run at around 8-10 FPS while the tiles are being rendered. If I turn off tile rendering than the system runs at 80 FPS (easy to run fast when there is nothing to do)
Do you have any ideas on how to speed up this process? I would like to see something at least around the 30 FPS mark to make this playable.
And finally although I am open to using 3rd party libraries to do this I would like to try and implement this logic myself before admitting defeat.
EDIT:
As requested here is the extra information for how the call for Image image = map.getTile(x, y).getImage(); works.
The map here come from the following TileMap class
TileMap.java
public class TileMap {
private Tile[][] tiles;
private LinkedList sprites;
private Sprite player;
private GraphicsConfiguration gc;
/**
Creates a new TileMap with the specified width and
height (in number of tiles) of the map.
*/
public TileMap(GraphicsConfiguration gc, int width, int height) {
this.gc = gc;
tiles = new Tile[width][height];
overlayer = new Tile[width][height];
sprites = new LinkedList();
}
/**
Gets the width of this TileMap (number of tiles across).
*/
public int getWidth() {
return tiles.length;
}
/**
Gets the height of this TileMap (number of tiles down).
*/
public int getHeight() {
return tiles[0].length;
}
/**
Gets the tile at the specified location. Returns null if
no tile is at the location or if the location is out of
bounds.
*/
public Tile getTile(int x, int y) {
if (x < 0 || x >= getWidth() ||
y < 0 || y >= getHeight())
{
return null;
}
else {
return tiles[x][y];
}
}
/**
* Helper method to set a tile. If blocking is not defined than it is set to false.
*
* #param x
* #param y
* #param tile
*/
public void setTile(int x, int y,Image tile){
this.setTile(x,y,tile,false);
}
/**
Sets the tile at the specified location.
*/
public void setTile(int x, int y, Image tile, boolean blocking) {
if(tiles[x][y] == null){
Tile t = new Tile(gc, tile, blocking);
tiles[x][y] = t;
}
else{
tiles[x][y].addImage(tile);
tiles[x][y].setBlocking(blocking);
}
}
...
With the Tile here being an instance of the following code. Essentially this class just holds the Image which can be updated by adding an overlay layer to it always using gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT); and a boolean to tell if it will block the player. The image that is passed in is also created in this manner.
Tile.java
public class Tile {
private Image image;
private boolean blocking = false;
private GraphicsConfiguration gc;
/**
* Creates a new Tile to be used with a TileMap
* #param image The base image for this Tile
* #param blocking Will this tile allow the user to walk over/through
*/
public Tile(GraphicsConfiguration gc, Image image, boolean blocking){
this.gc = gc;
this.image = image;
this.blocking = blocking;
}
public Tile(GraphicsConfiguration gc, Image image){
this.gc = gc;
this.image = image;
this.blocking = false;
}
/**
Creates a duplicate of this animation. The list of frames
are shared between the two Animations, but each Animation
can be animated independently.
*/
public Object clone() {
return new Tile(gc, image, blocking);
}
/**
* Used to add an overlay to the existing tile
* #param image2 The image to overlay
*/
public void addImage(Image image2){
BufferedImage base = (BufferedImage)image;
BufferedImage overlay = (BufferedImage)image2;
// create the new image, canvas size is the max. of both image sizes
int w = Math.max(base.getWidth(), overlay.getWidth());
int h = Math.max(base.getHeight(), overlay.getHeight());
//BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
BufferedImage combined = gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
// paint both images, preserving the alpha channels
Graphics g = combined.getGraphics();
g.drawImage(image, 0, 0, null);
g.drawImage(overlay, 0, 0, null);
this.image = (Image)combined;
}
public boolean isBlocking(){
return this.blocking;
}
public void setBlocking(boolean blocking){
this.blocking = blocking;
}
public Image getImage(){
return this.image;
}
}

I would use a pixel rendering engine (google it ;D)
Basically what you do, it have a giant array of intergers corresponding to the image you are drawing.
Basically you have each tile have an array of intergers representing its pixels.
When you render that tile, you "copy" (it's slightly more complicated than that) the array of tile to the big array :)
Then once you are done rendering everything to the master array, you draw that on the screen.
This way, you are only dealing with integers and not whole pictures everytime you draw something. This makes it a lot faster.
I learned this using MrDeathJockey's (youtube) tutorials and combining them with DesignsbyZephyr's (also youtube). Although I do not recommend using his technique (he only uses 4 colors and 8 bit graphics, as with deathJockey's tutorials you can customize the size of the images and even have multiple sprite sheets with different resolutions (useful for fonts)
I did however use some of the offset stuff (to make the screen move instead of the player) and the InputHandler by Zephyr :)
Hope this helps!
-Camodude009

Create transparent images (not translucent) since translucent images require higher ram and are stored in the system memory instead of the standard java heap. Creating translucent images require several native calls to access the native system memory. Use BufferedImages instead of Image. You can cast BufferedImage to Image at any time.

Related

How can I add a border to an image in Java?

The border needs to be made out of the closest pixel of the given image, I saw some code online and came up with the following. What am I doing wrong? I'm new to java, and I am not allowed to use any methods.
/**
* TODO Method to be done. It contains some code that has to be changed
*
* #param enlargeFactorPercentage the border in percentage
* #param dimAvg the radius in pixels to get the average colour
* of each pixel for the border
*
* #return a new image extended with borders
*/
public static BufferedImage addBorders(BufferedImage image, int enlargeFactorPercentage, int dimAvg) {
// TODO method to be done
int height = image.getHeight();
int width = image.getWidth();
System.out.println("Image height = " + height);
System.out.println("Image width = " + width);
// create new image
BufferedImage bi = new BufferedImage(width, height, image.getType());
// copy image
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pixelRGB = image.getRGB(x, y);
bi.setRGB(x, y, pixelRGB);
}
}
// draw top and bottom borders
// draw left and right borders
// draw corners
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pixelRGB = image.getRGB(x, y);
for (enlargeFactorPercentage = 0; enlargeFactorPercentage < 10; enlargeFactorPercentage++){
bi.setRGB(width, enlargeFactorPercentage, pixelRGB * dimAvg);
bi.setRGB(enlargeFactorPercentage, height, pixelRGB * dimAvg);
}
}
}
return bi;
I am not allowed to use any methods.
What does that mean? How can you write code if you can't use methods from the API?
int enlargeFactorPercentage
What is that for? To me, enlarge means to make bigger. So if you have a factor of 10 and your image is (100, 100), then the new image would be (110, 110), which means the border would be 5 pixels?
Your code is creating the BufferedImage the same size as the original image. So does that mean you make the border 5 pixels and chop off 5 pixels from the original image?
Without proper requirements we can't help.
#return a new image extended with borders
Since you also have a comment that says "extended", I'm going to assume your requirement is to return the larger image.
So the solution I would use is to:
create the BufferedImage at the increased size
get the Graphics2D object from the BufferImage
fill the entire BufferedImage with the color you want for the border using the Graphics2D.fillRect(….) method
paint the original image onto the enlarged BufferedImage using the Graphics2D.drawImage(…) method.
Hello and welcome to stackoverflow!
Not sure what you mean with "not allowed using methods". Without methods you can not even run a program because the "thing" with public static void main(String[] args) is a method (the main method) and you need it, because it is the program starting point...
But to answer your question:
You have to load your image. A possibility would be to use ImageIO. Then you create a 2D graphics object and then you can to drawRectangle() to create a border rectangle:
BufferedImage bi = //load image
Graphics2D g = bi.getGraphics();
g.drawRectangle(0, 0, bi.getHeight(), bi.getWidth());
This short code is just a hint. Try it out and read the documentation from Bufferedimage see here and from Graphics2D
Edit: Please notice that this is not quite correct. With the code above you overdraw the outer pixel-line from the image. If you don't want to cut any pixel of, then you have to scale it up and draw with bi.getHeight()+2 and bi.getWidth()+2. +2 because you need one pixel more at each side of the image.

Android piechart with icons between bars

I want to create a pie chart with images in between the legend bars. I am adding the screenshot below for better understanding, i tried using one canvas and then created one arc and tried to add images to it, but it was not working. For now i am using below pie chart library to show the bars with center text. Any suggestion will be helpful. Thanks :)
https://github.com/PhilJay/MPAndroidChart
enter image description here
Regards,
Rohit Garg
You can do that by extending PieChartRenderer.
If you look at the implementation of PieChartRenderer.drawRoundedSlices(Canvas c) you can get an example of how to get the starting coordinates of each slice.
Then just use drawBitmap or drawPicture to render your image between the pie slices. (I used Utils.drawImage in the example to mimic the source of PieChartRenderer)
As an example, i copied drawRoundedSlices and renamed it drawImageBeforeSlice. Instead of drawing the arcs, i draw bitmaps.
To make the renderer use the new method, i override drawExtras and stick a call to the new method on the end.
class PieChartRendererWithImages extends PieChartRenderer
{
protected Drawable mImage;
public PieChartRendererWithImages(PieChart chart, ChartAnimator animator, ViewPortHandler viewPortHandler, Drawable image) {
super(chart, animator, viewPortHandler);
mImage = image;
}
/**
* This draws an image before all pie-slices
*
* #param c
*/
protected void drawImageBeforeSlice(Canvas c) {
IPieDataSet dataSet = mChart.getData().getDataSet();
if (!dataSet.isVisible())
return;
float phaseX = mAnimator.getPhaseX();
float phaseY = mAnimator.getPhaseY();
MPPointF center = mChart.getCenterCircleBox();
float r = mChart.getRadius();
// calculate the radius of the "slice-circle"
float circleRadius = (r - (r * mChart.getHoleRadius() / 100f)) / 2f;
float[] drawAngles = mChart.getDrawAngles();
float angle = mChart.getRotationAngle();
for (int j = 0; j < dataSet.getEntryCount(); j++) {
float sliceAngle = drawAngles[j];
Entry e = dataSet.getEntryForIndex(j);
// draw only if the value is greater than zero
if ((Math.abs(e.getY()) > Utils.FLOAT_EPSILON)) {
float x = (float) ((r - circleRadius)
* Math.cos(Math.toRadians((angle + sliceAngle)
* phaseY)) + center.x);
float y = (float) ((r - circleRadius)
* Math.sin(Math.toRadians((angle + sliceAngle)
* phaseY)) + center.y);
// draw image instead of arcs
Utils.drawImage(
c,
mImage,
(int)x,
(int)y,
mImage.getIntrinsicWidth(),
mImage.getIntrinsicHeight());
}
angle += sliceAngle * phaseX;
}
MPPointF.recycleInstance(center);
}
#Override
public void drawExtras(Canvas c) {
super.drawExtras(c);
// use drawImageBeforeSlice in last step of rendering process
drawImageBeforeSlice(c);
}
}
Don't forget to set your new renderer on your PieChart:
myPieChart.setRenderer(new PieChartRendererWithImages(myPieChart, myPieChart.getAnimator(), myPieChart.getViewPortHandler(), getResources().getDrawable(R.drawable.my_image)));
Verified to work by putting it in the MPAndroidChart example:

How do I create an Area object using a PathIterator?

I am clearly missing an important concept here. I have written code using mouse events to draw a boundary (a polygon) on an existing BufferedImage. Here is the relevant section:
public void paintComponent(Graphics g)
{
super.paintComponent(g); //Paint parent's background
//G3 displays the BufferedImage "Drawing" with each paint
Graphics2D G3 = (Graphics2D)g;
G3.drawImage(this.Drawing, 0, 0, null);
G3.dispose();
}
public void updateDrawing()
{
int x0, y0, x1, y1; // Vertex coordinates
Line2D.Float seg;
// grafix is painting the mouse drawing to the BufferedImage "Drawing"
if(this.pts.size() > 0)
{
for(int ip = 0; ip < pts.size(); ip++)
{
x0 = (int)this.pts.get(ip).x;
y0 = (int)this.pts.get(ip).y;
this.grafix.drawRect(x0 - this.sqw/2, y0 - this.sqh/2, + this.sqw, this.sqh);
if (ip > 0)
{
x1 = (int)this.pts.get(ip-1).x;
y1 = (int)this.pts.get(ip-1).y;
this.grafix.drawLine(x1, y1, x0, y0);
seg = new Line2D.Float(x1, y1, x0, y0);
this.segments.add(seg);
}
}
}
repaint();
}
The next two routines are called by the mouse events: Left click gets the next point and right click closes the region.
public void getNextPoint(Point2D p)
{
this.isDrawing = true;
Point2D.Float next = new Point2D.Float();
next.x = (float) p.getX();
next.y = (float) p.getY();
this.pts.add(next);
updateDrawing();
}
public void closeBoundary()
{
//Connects the last point to the first point to close the loop
Point2D.Float next = new Point2D.Float(this.pts.get(0).x, this.pts.get(0).y);
this.pts.add(next);
this.isDrawing = false;
updateDrawing();
}
It all works fine and I can save the image with my drawing on it:
image with drawing
The list of vertices (pts) and the line segments (segments) are all that describe the region/shape/polygon.
I wish to extract from the original image only that region enclosed within the boundary. That is, I plan to create a new BufferedImage by moving through all of the pixels, testing to see if they fall within the figure and keep them if they do.
So I want to create an AREA from the points and segments I've collected in drawing the shape. Everything says: create an AREA variable and "getPathIterator". But on what shape? My AREA variable will be empty. How does the path iterator access the points in my list?
I've been all over the literature and this website as well.
I'm missing something.
Thank you haraldK for your suggestion. Before I saw your post, I came to a similar conclusion:
Using the Arraylist of vertices from the paint operation, I populated a "Path2D.Float" object called "contour" by looping through the points list that was created during the "painting" operation. Using this "contour" object, I instantiated an Area called "interferogram". Just to check my work, I created another PathIterator, "PI", from the Area and decomposed the Area, "interferogram" into "segments" sending the results to the console. I show the code below:
private void mnuitmKeepInsideActionPerformed(java.awt.event.ActionEvent evt)
{
// Keeps the inner area of interest
// Vertices is the "pts" list from Class MouseDrawing (mask)
// It is already a closed path
ArrayList<Point2D.Float> vertices =
new ArrayList<>(this.mask.getVertices());
this.contour = new Path2D.Float(Path2D.WIND_NON_ZERO);
// Read the vertices into the Path2D variable "contour"
this.contour.moveTo((float)vertices.get(0).getX(),
(float)vertices.get(0).getY()); //Starting location
for(int ivertex = 1; ivertex < vertices.size(); ivertex++)
{
this.contour.lineTo((float)vertices.get(ivertex).getX(),
(float)vertices.get(ivertex).getY());
}
this.interferogram = new Area(this.contour);
PathIterator PI = this.interferogram.getPathIterator(null);
//Test print out the segment types and vertices for debug
float[] p = new float[6];
int icount = 0;
while( !PI.isDone())
{
int type = PI.currentSegment(p);
System.out.print(icount);
System.out.print(" Type " + type);
System.out.print(" X " + p[0]);
System.out.println(" Y " + p[1]);
icount++;
PI.next();
}
BufferedImage masked = Mask(this.image_out, this.interferogram);
// Write image to file for debug
String dir;
dir = System.getProperty("user.dir");
dir = dir + "\\00masked.png";
writeImage(masked, dir, "PNG");
}
Next, I applied the mask to the image testing each pixel for inclusion in the area using the code below:
public BufferedImage Mask(BufferedImage BIM, Area area)
{
/** Loop through the pixels in the image and test each one for inclusion
* within the area.
* Change the colors of those outside
**/
Point2D p = new Point2D.Double(0,0);
// rgb should be white
int rgb = (255 << 24);
for (int row = 0; row < BIM.getWidth(); row++)
{
for (int col = 0; col < BIM.getHeight(); col++)
{
p.setLocation(col, row);
if(!area.contains(p))
{
BIM.setRGB(col, row, rgb);
}
}
}
return BIM;
}
public static BufferedImage deepCopy(BufferedImage B2M)
{
ColorModel cm = B2M.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = B2M.copyData(B2M.getRaster()
.createCompatibleWritableRaster());
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
This worked beautifully (I was surprised!) except for one slight detail: the lines of the area appeared around the outside of the masked image.
In order to remedy this, I copied the original (resized) image before the painting operation. Many thanks to user1050755 (Nov 2014) for the routine deepCopy that I found on this website. Applying my mask to the copied image resulted in the portion of the original image I wanted without the mask lines. The result is shown in the attached picture. I am stoked!
masked image

Java - Sprite in JPanel error

Every time i run the panel is filled with a white line in the corner of it and the rest is black.
I would like to add KeyListener to the program so when i push the "W" key it will animate the sprite as it seems to be going forward.
IF the sprite is not centered all the time than how would i code a collision detect to repaint the map when the sprite image block reaches the edge of the panel.
I know im asking more than one question yet im tring to figure out one problem.
How would i spawn a simple NPC at a specific location on the tiled map that has not yet been painted. Have this NPC to be intractable.
What I would like to do is have a sprite in the center of the screen. Have a tiled map in the background with collision detect depended on color squares. IF tile layer is colored red not allow to pass through IF tile layer is colored red allow to pass through If tile color yellow apply action for it is a treasure chest.
public class gamePanel extends JPanel {
private BufferedImage image;
public gamePanel() throws IOException{
this.setBackground(Color.red);
}
public static void loadMap(Graphics g, int frame){
try {
BufferedImage bigImg = ImageIO.read(new File("C:\\Users\\czar\\Documents\\NetBeansProjects\\Inter\\src\\inter\\menu.jpg"));
} catch (IOException ex) {
Logger.getLogger(gamePanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void loadSprite(Graphics g, int move_int) throws IOException{
BufferedImage bigImg = ImageIO.read(new File("C:\\Users\\czar\\Documents\\NetBeansProjects\\Inter\\src\\inter\\sprite.jpg"));
// The above line throws an checked IOException which must be caught.
final int width = 25;
final int height = 40;
final int cols = 2;
BufferedImage[] left_move = new BufferedImage[3];
BufferedImage[] right_move = new BufferedImage[3];
BufferedImage[] up_move = new BufferedImage[3];
BufferedImage[] down_move = new BufferedImage[3];
for(int i = 0; i < 4; i++){
if(move_int == 0){
left_move[i] = bigImg.getSubimage(
0 * width, 0 * height, width, height );
}
if(move_int == 1){
right_move[i] = bigImg.getSubimage(
i * width, 1 * height, width, height );
}
if(move_int == 2){
up_move[i] = bigImg.getSubimage(
i * width, 2 * height, width, height );
}
if(move_int == 3){
down_move[i] = bigImg.getSubimage(
i * width, 3 * height, width, height );
}
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
try {
loadMap(g, 0);
loadSprite(g, 0);
} catch (IOException ex) {
// handle exception...
}
}
}
I'm not really sure what you're trying to do, but here is some quick help on solving your error.
This code...
BufferedImage[] down_move = new BufferedImage[3];
creates an array which can hold 3 images, namely:
down_move[0]
down_move[1]
down_move[2]
That is because arrays are zero-based. If you do:
System.out.println(down_move.length);
you will see it output 3. This is because your array only fits 3 images.
I assume you want 4 images on your array. Therefore you will need to modify your code to:
BufferedImage[] down_move = new BufferedImage[4];
This will result in 4 images, namely:
down_move[0]
down_move[1]
down_move[2]
down_move[3]
In your code you are trying to access down_move[3] in an array that only goes up to down_move[2].
Read the error: ArrayIndexOutOfBoundsException: 3
Your image arrays have 3 indices (0, 1, and 2), and somewhere you're trying to access the 4th index (3).
Change your image array sizes to 4 instead of 3 (as shown below) and it should no longer give you this exception.
BufferedImage[] up_move = new BufferedImage[4];
BufferedImage[] down_move = new BufferedImage[4];
BufferedImage[] left_move = new BufferedImage[4];
BufferedImage[] right_move = new BufferedImage[4];

Rotate BufferedImage

I'm following a textbook and have become stuck at a particular point.
This is a console application.
I have the following class with a rotate image method:
public class Rotate {
public ColorImage rotateImage(ColorImage theImage) {
int height = theImage.getHeight();
int width = theImage.getWidth();
//having to create new obj instance to aid with rotation
ColorImage rotImage = new ColorImage(height, width);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
Color pix = theImage.getPixel(x, y);
rotImage.setPixel(height - y - 1, x, pix);
}
}
//I want this to return theImage ideally so I can keep its state
return rotImage;
}
}
The rotation works, but I have to create a new ColorImage (class below) and this means I am creating a new object instance (rotImage) and losing the state of the object I pass in (theImage). Presently, it's not a big deal as ColorImage does not house much, but if I wanted it to house the state of, say, number of rotations it has had applied or a List of something I'm losing all that.
The class below is from the textbook.
public class ColorImage extends BufferedImage {
public ColorImage(BufferedImage image) {
super(image.getWidth(), image.getHeight(), TYPE_INT_RGB);
int width = image.getWidth();
int height = image.getHeight();
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
setRGB(x, y, image.getRGB(x, y));
}
public ColorImage(int width, int height) {
super(width, height, TYPE_INT_RGB);
}
public void setPixel(int x, int y, Color col) {
int pixel = col.getRGB();
setRGB(x, y, pixel);
}
public Color getPixel(int x, int y) {
int pixel = getRGB(x, y);
return new Color(pixel);
}
}
My question is, how can I rotate the image I pass in so I can preserve its state?
Unless you limit yourself to square images or to 180° rotations, you need a new object, as the dimensions would have changed. The dimensions of a BufferedImage object, once created, are constant.
If I wanted it to house the state of, say, number of rotations it has had applied or a List of something I'm losing all that
You can create another class to hold that other information along with the ColorImage/BufferedImage, then limit the ColorImage/BufferedImage class itself to holding only the pixels. An example:
class ImageWithInfo {
Map<String, Object> properties; // meta information
File file; // on-disk file that we loaded this image from
ColorImage image; // pixels
}
Then you can replace the pixels object freely, while preserving the other state. It's often helpful to favor composition over inheritance. In brief that means, instead of extending a class, create a separate class that contains the original class as a field.
Also note that the rotation implementation from your book seems to be mainly for learning purposes. It's fine for that, but will show its performance limitations if you manipulate very big images or for continuous graphics rotation at animation speeds.

Categories