Java 从Graphics2D几何体对象获取实际绘制的像素

Java 从Graphics2D几何体对象获取实际绘制的像素,java,graphics,applet,shape,graphics2d,Java,Graphics,Applet,Shape,Graphics2d,我在Graphics2D对象中绘制几何体对象(在本例中为简单线),如下所示: Graphics2D g2d = (Graphics2D) g; g2d.setStroke(new BasicStroke(width)); Line2D.Double line = new Line2D.Double(oldPosition.x, oldPosition.y, newPosition.x, newPosition.y);

我在Graphics2D对象中绘制几何体对象(在本例中为简单线),如下所示:

Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(width));
Line2D.Double line = new Line2D.Double(oldPosition.x, oldPosition.y, 
                                       newPosition.x, newPosition.y);
g2d.draw(connectionLine);
是否有可能从线条形状中获得实际绘制的像素?我查阅了很多文件,但什么也没找到。我找到的最近的对象是PathIterator,但这也不能解决我的问题

PathIterator pi = connectionLine.getPathIterator(new AffineTransform());
while (!pi.isDone()) {
    double[] coords = new double[6];
    pi.currentSegment(coords);
    System.out.println(Arrays.toString(coords));
    pi.next();
}
// OUTPUT (line was painted from (20,200) to (140,210): 
// [20.0, 200.0, 0.0, 0.0, 0.0, 0.0]
// [140.0, 210.0, 0.0, 0.0, 0.0, 0.0]
有没有什么方法可以返回一个真正绘制的像素坐标数组?如果没有,你有什么建议吗?自己实现算法容易吗(请记住,线条的宽度大于1像素)?或者我应该在一个新的空白(白色)图像上画一条线,这样我就可以分别迭代每个像素,检查他是否是白色的(听起来很奇怪

如果能给我一个有用的答复,我将不胜感激——致以最良好的问候,
Felix

至少,我自己找到了一个解决方案,虽然不是很好,但比画第二张临时图像要好。该解决方案意味着您希望获得具有圆形起点和终点的Line2D对象的像素:

private void getPaintedPixel(Line2D.Double line,
        double lineWidth) {
    // get the corner coordinates of the line shape bound
    Rectangle2D bound2D = line.getBounds2D();
    double yTop = bound2D.getY() - lineWidth;
    double yBottom = bound2D.getY() + bound2D.getHeight() + lineWidth;
    double xLeft = bound2D.getX() - lineWidth;
    double xRight = bound2D.getX() + bound2D.getWidth() + lineWidth;

    // iterate over every single pixel in the line shape bound
    for (double y = yTop; y < yBottom; y++) {
        for (double x = xLeft; x < xRight; x++) {
            // calculate the distance between a particular pixel and the
            // painted line
            double distanceToLine = line.ptSegDist(x, y);
            // if the distance between line and pixel is less then the half
            // of the line width, it means, that the pixel is a part of the
            // line
            if (distanceToLine < lineWidth / 2) {
                // pixel belongs to the line
            }
        }
    }
}
private void getPaintedPixel(Line2D.Double line,
双线宽){
//获取线条形状边界的角坐标
矩形2D bound2D=line.getBounds2D();
double yTop=bound2D.getY()-线宽;
double yBottom=bound2D.getY()+bound2D.getHeight()+线宽;
double xLeft=bound2D.getX()-线宽;
double xRight=bound2D.getX()+bound2D.getWidth()+lineWidth;
//迭代线条形状边界中的每个像素
对于(双y=yTop;y

显然,在线条边界内迭代每个像素仍然有点尴尬,但我找不到更好的方法,只要绘制的线条不是太大,在性能方面就可以了

将形状绘制为透明缓冲区,从光栅中提取像素…好,这将是我最后一个选项中描述的解决方案。你们是对的,在一个透明的图像上绘制它可以解决这个问题,但遍历一个临时创建的图像的所有像素似乎不是一个好的解决方案——所以我会等待并希望,任何人都可以建议一个更好的解决方案,它可能也有更好的性能。当涉及到从后缓冲区读取像素时,这不是一个好的解决方案