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