微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何为每个像素创建更好的嵌套循环?

如何解决如何为每个像素创建更好的嵌套循环?

我要创建的是高分辨率元球。 这是我的算法:

public constructor(){
        this.image = new BufferedImage(this.getWidth(),this.getHeight(),BufferedImage.TYPE_INT_ARGB);
        this.rgbRaster = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
        this.width = getWidth();
        this.height = getHeight();
}

private void updateraster() {
        int red = c.getRed(),green = c.getGreen(),blue = c.getBlue();

        for (int y = 0; y < height; y++)
            for (int x = 0; x < width; x++) {
                var sum = 0f;
                for (Blob b : blobs)
                    sum += getSum(x,y,b);

                sum = Math.min(sum,255) / 255f;

                rgbRaster[(width * y) + x] = ((0xFF) << 24) | (((int) (sum * red) & 0xFF) << 16) |
                        (((int) (sum * green) & 0xFF) << 8) | (((int) (sum * blue)) & 0xFF);
            }
    }
private float getSum(int x,int y,Blob b) {
        var d = Point.distance(x,b.pos.x,b.pos.y);
        return (float) map(1000f * b.r / d,this.maxdist,255);
    }

private double map(double n,double start1,double stop1,double start2,double stop2) {
        return (n - start1) / (stop1 - start1) * (stop2 - start2) + start2;
    }

Blob类非常简单,它只是一个从屏幕上反弹的球:

public class Blob {
    public Vector2D pos;
    public Vector2D vel;
    public float r;

    public Blob(Vector2D pos,Vector2D vel,float r) {
        this.pos = pos;
        this.vel = vel;
        this.r = r;
    }

    public void update(float w,float h) {
        this.pos.add(vel);
        this.bounds(w,h);
    }

    public void draw(Graphics2D g) {
        g.fill(new Ellipse2D.Double(this.pos.x - r,this.pos.y - r,r * 2,r * 2));
    }

    private void bounds(float w,float h) {
        if (this.pos.x + r > w || this.pos.x - r < 0) this.vel.mult(new Vector2D(-1,1));
        if (this.pos.y + r > h || this.pos.y - r < 0) this.vel.mult(new Vector2D(1,-1));
    }
}

问题在于,嵌套循环中的迭代次数过多,这会导致严重冻结。 我无法弄清楚从屏幕的每个像素到所有斑点的中心点都存在细微差别的其他方式,因此在高分辨率图片和大量斑点的情况下,它就可以像幻灯片一样显示。我也知道将所有内容转换为BufferedImage并不是一个完美的主意,但我不知道将栅格转换为图形对象的其他方法。预先感谢您的帮助)(编辑:getSum()找到所有斑点的总和,将其映射到颜色范围,并将其限制为255。此函数当然不是问题,但有点复杂,理解这就是为什么我没有包含它)(编辑2:感谢@ThatOtherGuy现在以这种方式更加优化,但可能还有其他错误

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。