I need to write a flood fill algorithm to color pixels of an image which are inside black borders. I've wrote the following based on some posts here on SO:
private Queue<Point> queue = new LinkedList<Point>();
private int pickedColorInt = 0;
private void floodFill(Pixmap pixmap, int x, int y){
//set to true for fields that have been checked
boolean[][] painted = new boolean[pixmap.getWidth()][pixmap.getHeight()];
//skip black pixels when coloring
int blackColor = Color.rgba8888(Color.BLACK);
queue.clear();
queue.add(new Point(x, y));
while(!queue.isEmpty()){
Point temp = queue.remove();
int temp_x = temp.getX();
int temp_y = temp.getY();
//only do stuff if point is within pixmap's bounds
if(temp_x >= 0 && temp_x < pixmap.getWidth() && temp_y >= 0 && temp_y < pixmap.getHeight()) {
//color of current point
int pixel = pixmap.getPixel(temp_x, temp_y);
if (!painted[temp_x][temp_y] && pixel != blackColor) {
painted[temp_x][temp_y] = true;
pixmap.drawPixel(temp_x, temp_y, pickedColorInt);
queue.add(new Point(temp_x + 1, temp_y));
queue.add(new Point(temp_x - 1, temp_y));
queue.add(new Point(temp_x, temp_y + 1));
queue.add(new Point(temp_x, temp_y - 1));
}
}
}
}
This doesn't work as expected. For example, on following test image:
Random rectangles will get recolored depending of where I've clicked. For example, clicking anywhere below purple rectangle will recolor purple rectangle. Clicking inside purple rectangle recolors the green rectangle. I've checked it and I'm passing right parameters to method so the issue is probably somewhere inside my loop.
Your algorithm is correct, only your input parameters are not.
Random rectangles will get recolored depending of where I've clicked. For example, clicking anywhere below purple rectangle will recolor purple rectangle. Clicking inside purple rectangle recolors the green rectangle.
If you look at the picture, the colored rectangles are not really random. The real problem is an incorrect Y-coordinate. Specifically your Y-coordinate is inverted.
That's because most of the time LibGDX uses a lower-left, y-up coordinate system, but in case of Pixmap it is top-left y-down.
A simple fix for this is to just invert the Y-value by doing y = pixmap.getHeight() - y.
Related
So I have to use java.awt.color to flip some imported images.
Here is my primary method to achieve flipping an image over the vertical axis:
public void execute (Pixmap target)
{
Dimension bounds = target.getSize();
// TODO: mirror target image along vertical middle line by swapping
// each color on right with one on left
for (int x = 0; x < bounds.width; x++) {
for (int y = 0; y < bounds.height; y++) {
// new x position
int newX = bounds.width - x - 1;
// flip along vertical
Color mirrorVert = target.getColor(newX, y);
target.setColor(x, y, new Color (mirrorVert.getRed(),
mirrorVert.getGreen(),
mirrorVert.getBlue()));
}
}
}
However, when this executes, instead of the image, flipping, I get something like this:
Original:
"Flipped":
Thank y'all for the help
// flip along vertical
Color mirrorVert = target.getColor(newX, y);
target.setColor(x, y, new Color (mirrorVert.getRed(),
mirrorVert.getGreen(),
mirrorVert.getBlue()));
target.setColor(newX, y , new Color(255,255,255));
}
This should work in theory. Basically the idea is to set the Colors on the right side to white, while copying it over to the left side.
Actually this will not work... So what you could do is to save the new colors in an array. Then you can make everything white and put the swapped colors back.
for (int i=0;i<image.getWidth();i++)
for (int j=0;j<image.getHeight();j++)
{
int tmp = image.getRGB(i, j);
image.setRGB(i, j, image.getRGB(i, image.getHeight()-j-1));
image.setRGB(i, image.getHeight()-j-1, tmp);
}
That one looks promising.
What I am trying to achieve is getting a mask of an image, converting it into an Array with the dimensions (image.getWidth(), image.getHeight()), then getting all the pixels and seeing if they have an alpha value of 0.
IF they do, then:
add value 1 for the x, y co-ordinate that I am examining at the moment.
ELSE:
add value 0 for the x, y co-ordinate that I am examining at the moment.
Up to this point, I know how to program this. If you are interested, this is the code I am using:
private int[] createMask(BufferedImage image) {
final int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
final int width = image.getWidth();
final int height = image.getHeight();
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
int[][] result = new int[height][width];
if (hasAlphaChannel) {
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += 4) {
int alpha = pixels[pixel];
if(alpha != 0) {
result[row][col] = 1;
} else {
result[row][col] = 0;
}
if (col == width) {
col = 0;
row++;
}
}
}
return result;
}
After I get this mask, I am attempting to use this Array to draw a Polygon via this code, or an alternation of it (obtained from http://docs.oracle.com/javase/tutorial/2d/geometry/arbitrary.html) :
int x1Points[] = {0, 100, 0, 100};
int y1Points[] = {0, 50, 50, 0};
GeneralPath polygon =
new GeneralPath(GeneralPath.WIND_EVEN_ODD,
x1Points.length);
polygon.moveTo(x1Points[0], y1Points[0]);
for (int index = 1; index < x1Points.length; index++) {
polygon.lineTo(x1Points[index], y1Points[index]);
};
polygon.closePath();
g2.draw(polygon);
However, I need to create a method which gives me all the co-ordinates in an Array consisting of Point objects to go around the image to essentially create a "mask".
public Point[] getCords(int[] mask) {
ArrayList<Point> points = new ArrayList<Point>(); //you can change this to whatever you want to use
//get coords to surround the mask
// >> involving `0` (for transparent) and `1` (non transparent)
// >> these are contained in the `mask` Array...
return points.toArray(new Points[0]);
So, to conclude:
I require to obtain a polygon that outlines an image's visible pixels from an int[] array which contains the values 1's and 0's, the former for non-transparent pixel and latter for transparent pixel, respectively.
(link to related java code below)
To create the mask border, do the following: for each pair of coordinates (x,y) check if any one of 8 its neighboring points is outside the mask. However, keep in mind that the resulting mask isn't necessarily 1 pixel wide and vectorizing it might be non-trivial, as in this example (white is the masked area, red is the mask border inside the mask, black is unmasked area):
Luckily, even if you get a wider-than-1-pixel border in some places in your mask, you can workaround that by rejecting some pixels of the mask from that mask building a submask that is polygonizable. The following image shows the submask's border in blue:
I implemented such algorithm a while ago. There is the code you can use, but it is quite tightly coupled with my solution, however you could find some insights in it: Thick mask border resolution. Its idea is that from the initial mask you build a submask by flood-filling original mask with a predicate that checks that a cell of submask's border has at most 2 cardinal direction neighbors (ordinal direction neighbors don't matter here).
Once you got the blue submask's border, build a graph where vertices are points of submask's border, and edges are between cardinally neighboring points. Then traverse each component of that graph, and for each component you get a list of points that form your polygons.
I'm creating a game and I have a JFrame with a custom Canvas in it. The weird thing is that when I set the JFrame to BE RESIZABLE, the rendering result looks like this:
But when I set the JFrame to NOT BE RESIZABLE, the result looks like this:
The method which adds the texture's pixel array to the BufferedImage's pixel array looks like this:
// DRAW A TEXTURE ON THE CANVAS
public void drawTexture(Texture texture, Vector2i location) {
// Store the current texture coordinates
int tx = 0, ty = 0;
// Scroll through each pixel on the screen horizontally (begin at the X coordinate specified by the 'location')
for(int x = location.x; (x < getWidth() && x < location.x + texture.getWidth()); x++) {
// Scroll through each pixel on the screen vertically (begin at the Y coordinate specified by the 'location')
for(int y = location.y; (y < getHeight() && y < location.y + texture.getHeight()); y++) {
// Set each pixel to the color of the corresponding pixel on the Texture
pixels[x + y * getWidth()] = texture.getPixels()[tx + ty * texture.getWidth()];
// Add one to the texture Y coordinate
ty++;
}
// Reset the ty variable
ty = 0;
// Add one to the texture X coordinate
tx++;
}
}
And the BufferedImage is drawn inside of a loop in the run method of my custom canvas.
The custom canvas class (extends Canvas offcourse) implements Runnable, and it also contains an own Thread for rendering.
I wonder if anyone know why this happens, and maybe how to fix it, because I can't figure it out...
Well, I found the working answer here, because I found out that the Canvas was bigger than what I had set it to, so I googled for that, and that answer fixed both problems.
Quote from the answer to the other question:
Swap the pack and setResizable calls, so that pack is the second call.
and
This is a known "issue"
Question here.
Some Context:
I am creating an Android game which draws a maze onto a canvas against a background image, this uses a square block and therefore the maze is always automtically zoomed in to a 5 x 5 square, of a maze that may be 20 x 20. The maze is drawn by simply running through a set of for loops and then drawing lines in the relevent places. This is all working perfectly, however I am having an issue with getting my onDraw to work smoothly. This is occuring due to the fact that everytime I invalidate I have to re-run the for look and run various if statements to check positions (unfortunetly this process cannot be improved).
The Question:
I am looking to re-write the way my maze is drawn onto the canvas, below are the 3 main features I need to implement:
1 - Draw the whole maze onto the canvas (this is easy enough)
2 - Zoom in on the maze so only a 5 x 5 is shown
3 - Move the character (who is always centered on the screen) and draw the next seciton of the maze
Now as mentioned above drawing the whole maze is easy enough and will make the onDraw signifcatly quicker as their is no need to run the for loop on invaldate, it can be done once when the level is first loaded up.
In terms of point 2 & 3, the way I see this working is the charcacter to be drawn in the middle of the canvas then a 2d birdseye view camera to be attached / linked to the characters movement. This camera would also need to be zoomed in to an extent that it only displays a 5 x 5 of the overall maze grid. Then as the charcater moves the camera moves with the character and displays the next section of the maze which has already been drawn. I have tried a few things and done some reasearch however I have never worked with canvas before and no idea really where to start and if this is even possible.
So to sum up the main part of the question is whether their is a way to link a birdseye view camera to a character which is zoomed in and moves with the character image.
Below is a snippet as to how the maze is currently drawn, using 2 sets of for loops checking against 2 sets of boolean arrays[][], which simply store the vertical and horixaonl lines to be drawn.
#Override
protected void onDraw(Canvas canvas)
{
canvas.drawRect(0, 0, width, 100, background);
RectBackground.set(0,0, FullScreenWidth, FullScreenWidth);
canvas.drawBitmap(gameBackground, null, RectBackground, null);
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
float x = j * totalCellWidth;
float y = i * totalCellHeight;
indexY = i + currentY;
indexX = j + currentX;
// Draw Verticle line (y axis)
if (indexY < vLength && indexX < vLines[indexY].length && vLines[indexY][indexX])
{
RectOuterBackground.set((int)x + (int)cellWidth, (int)y, (int)x + (int)cellWidth + 15, (int)y + (int)cellHeight + 15);
canvas.drawBitmap(walls, null, RectOuterBackground, null);
}
// Draws Horizontal lines (x axis)
if (indexY < hLength && indexX < hLines[indexY].length && hLines[indexY][indexX])
{
RectOuterBackground.set((int)x, (int)y + (int)cellHeight,(int)x + (int)cellWidth + 15,(int)y + (int)cellHeight + 15);
canvas.drawBitmap(walls, null, RectOuterBackground, null);
}
}
}
}
To make the drawing faster, you can double buffer the canvas by drawing directly into a bitmap and flashing the bitmap into the canvas like this. It's very fast.
private void init()
{
//variables below are class-wide variables
b = Bitmap.createBitmap(cwidth, cheight, Bitmap.Config.ARGB_8888);
bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bitmapPaint.setStyle(Paint.Style.STROKE);
bitmapPaint.setStrokeWidth(3);
myPaint.setColor(0xff000000);
myCanvas = new Canvas(b);
}
protected void onDraw(Canvas c)
{
super.onDraw(c);
c.drawBitmap(b, 0, 0, myPaint);
for(int i = 0; i < number lines; i++)
{
//draw here using myPath
}
if(b != null)
c.drawBitmap(b, 0, 0, myPaint);
myCanvas.drawPath(myPath, bitmapPaint);
}
Then, to "move around" I would suggest using a crop box. What this means is that a 1:1 scale, the image is larger than the viewport displayed on the screen. Really what's happening when someone "moves" is the bitmap is being moved beneath the crop box.
You could use BitmapRegionDecoder and display only the region the character is in (this might be slowish) or by using
public void drawBitmap (Bitmap bitmap, Rect src, RectF dst, Paint paint)
The src parameter here allows you to specify a small region of the bitmap to display. It is effectively a crop box.
To zoom in and out you need to multiply the coordinates by a number( zoom factor)
int x1 = (int)x + (int)cellWidth;
int y1 = (int)y;
int x2 = (int)x + (int)cellWidth + 15;
int y2 = (int)y + (int)cellHeight + 15;
RectOuterBackground.set(x1*zoom, y1*zoom, x2*zoom, y2*zoom);
note that zoom must be a floating point number, using zoom=2 that makes everything twice as big.
if you want to put the camera on top of the cell (xc, yc) you need to do this:
RectOuterBackground.set( (x1-xc)*zoom, (y1-yc)*zoom, (x2-xc)*zoom, (y2-yc)*zoom);
Try first drawing the whole maze, and soon you will figure out how to only draw the bit of the maze that is only inside the screen
I hope this helps and let me know if you have any questions :)
I'm using LWJGL and Slick2D for a game I'm making. I can't seem to get it to draw the way I want it to be draw so I came up with an idea just to make my own drawing method. Basically it takes a image, a x, and a y and it goes through each pixel in the image, gets the color, then draws the image with the parameter x plus the x pixel it's on to get the position that the pixel is suppost to be drawn on. Same idea with the y. Although if the alpha channel isn't 255 for the pixel it doesn't draw it, although I'll fix that later. The problem is that whenever I run my code I get "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -2044". I'm really confused. I'm hoping someone can figure out why this is happening.
private void DrawImage(Image image, int xP, int yP)
{
//xP And yP Are The Position Parameters
//Begin Drawing Individual Pixels
glBegin(GL_POINTS);
//Going Across The X And The Y Coords Of The Image
for (int x = 1; x <= image.getWidth(); x++)
{
for (int y = 1; y <= image.getHeight(); y++)
{
//Define A Color Object
Color color = null;
//Set The Color Object And Check If The Color Is Completly Solid Before Rendering
if ((color = image.getColor(x, y)).a == 255)
{
//Bind The Color
color.bind();
//Draw The Color At The Coord Parameters And The X/Y Coord Of The Individual Pixel
glVertex2i(xP + x - 1, yP + y - 1);
}
}
}
glEnd();
}
My answer is assuming that the texture is an array of data.
I have a feeling it is the getColor() method. Your for loop runs through and will use the height and width values. An array usually starts off with 0 and width and height are just array counts typically. So I can see when you reach HEIGHT, that the texture array will throw an exception.
Try removing the <= part and replace it with <
EXAMPLE:
for (int x = 1; x < image.getWidth(); x++)
It may also help you to start off with zero so you can get the entire image.
EXAMPLE
for (int x = 0; x < image.getWidth(); x++)
Here is a link on arrays.
This way, when you ask for the color at whatever position, it will never ask for a color reaching beyond what is in the texture array. Hopefully I made sense.