这可能不是最快或设计最好的方法,但它会接受消费者,您可以在其中对 Point 对象进行操作,从图像中间螺旋循环直到到达最后一个角落。图片不必是方形的。
import java.awt.*;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
SpiralLoop.loop((Point p) -> System.out.println(p.x + "," + p.y), 500, 200);
}
}
class SpiralLoop{
public static void loop(Consumer<Point> consumer, int maxX, int maxY ) {
int middleX = maxX/2;
int middleY = maxY/2;
Set<Point> edgesLeft = new HashSet<>();
edgesLeft.add(new Point(0,0));
edgesLeft.add(new Point(0,maxY));
edgesLeft.add(new Point(maxX,0));
edgesLeft.add(new Point(maxX,maxY));
MovingPoint currentPoint = new MovingPoint(middleX, middleY,maxX,maxY);
Set<Point> pointsDone = new HashSet<>();
pointsDone.add(new Point(currentPoint.x,currentPoint.y));
int directionIndex = 0;
int length = 1;
boolean lengthFlag = true;
while(!edgesLeft.isEmpty()){
for(int i=0; i<length;i++){
switch(directionIndex){
case 0 : currentPoint.moveLeft(); break;
case 1 : currentPoint.moveUp(); break;
case 2 : currentPoint.moveRight(); break;
case 3 : currentPoint.moveDown(); break;
}
if(pointsDone.contains(currentPoint)){
continue;
}
pointsDone.add(new Point(currentPoint.x,currentPoint.y));
consumer.accept(currentPoint);
if(edgesLeft.contains(currentPoint)){
edgesLeft.remove(currentPoint);
if(edgesLeft.isEmpty()){
break;
}
}
}
if(++directionIndex > 3){
directionIndex = 0;
}
if((lengthFlag = !lengthFlag)){
length++;
}
}
}
static class MovingPoint extends Point{
private int maxX;
private int maxY;
MovingPoint(int x, int y, int maxX, int maxY){
super(x,y);
this.maxX = maxX;
this.maxY = maxY;
}
void moveUp(){
if(this.y != 0){
this.y--;
}
}
void moveDown(){
if(this.y != maxY){
this.y++;
}
}
void moveRight(){
if(this.x != maxX){
this.x++;
}
}
void moveLeft(){
if(this.x != 0){
this.x--;
}
}
}
}
从您的代码中处理图像看起来有点类似于:
here :{
SpiralLoop.loop((Point p) -> {
int color = image.getRGB(p.x, p.y);
int red = (color & 0x00ff0000) >> 16;
int green = (color & 0x0000ff00) >> 8;
int blue = color & 0x000000ff;
if (red == 255) {
System.out.println("Red has been found inside the picture");
break here;
}
}), image.width, image.height);
}