我在 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 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 个像素)?或者我应该在一个新的空白(白色)图像上画线,这样我就可以单独迭代每个像素并检查他是否是白色的(听起来很奇怪......
我真的很感激一个有用的答案 - 最好的问候,费利克斯
至少,我自己找到了一个解决方案,不是一个非常好的解决方案,但比绘制第二个临时图像要好。该解决方案意味着您希望获取具有圆形起点和终点的 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
}
}
}
}
显然,迭代线边界内的每个像素仍然有点尴尬,但我找不到更好的方法,只要涂漆的线不是太大,在性能方面就可以了。