我正在制作一个有点像Paint
light 的程序,并且我已经达到了我希望用户能够选择椭圆区域的程度。我最初的想法是,必须有某种方程可以让我根据矩形的宽度和高度构造椭圆。然而,到目前为止我还没有发现任何如此直接的东西。
这是我在用户拖动鼠标时选择矩形区域的代码(位于 MouseAdapter 内部):
@Override
public void mouseDragged(MouseEvent e) {
dragPoint = e.getPoint();
if (selectionType.equalsIgnoreCase("Rectangle")) {
int width = dragPoint.x - mouseAnchor.x;
int height = dragPoint.y - mouseAnchor.y;
subHeight = height;
subWidth = width;
int x = mouseAnchor.x;
int y = mouseAnchor.y;
if (width < 0) {
x = dragPoint.x;
width *= -1;
}
if (height < 0) {
y = dragPoint.y;
height *= -1;
}
selectionPane.setBounds(x, y, width, height);
selectionPane.revalidate();
repaint();
}
}
SelectionPane
是扩展 JPanel
的自定义类的实例。我的想法是,我想从所选区域绘制一个填充的椭圆,以便用户可以看到他们选择的内容。
这个程序的第二部分也是我遇到一些困惑的地方。用户做出选择后,我想使用所选区域作为指导将蒙版应用于图像位。所以我也在使用字节数组。如何根据子图像的宽度、高度和原点找到计算出的椭圆形中包含哪些字节?下面是我根据矩形选区获取子图像的代码(仅供引用):
@Override
public void mouseReleased(MouseEvent e) {
if (subWidth != 0 && subHeight != 0) {
try {
//numCols * (numRows - 1) + xPos
int startPos = img.getWidth() * (img.getHeight() - 1) + mouseAnchor.x;//the starting position for the total byte array of the original image. The mask will start here.
Main.setStartingPos(startPos);
Main.setSubImage(img.getSubimage(mouseAnchor.x, mouseAnchor.y, Math.abs(subWidth), Math.abs(subHeight)));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(Main.getSubImage(), "bmp", baos);
Main.setImageRegion(baos.toByteArray()); //sets the region bytes in the Main class
Main.generateImageMask();//generates the mask after everything's been calculated.
} catch (IOException ex) {
Logger.getLogger(SelectionRectangle.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
如果有什么办法可以让我的问题更清楚,请告诉我。
最佳答案
您可以按如下方式从矩形中获取椭圆:
Ellispe2D.Double el=new Ellispe2D.Double(x, y, width, height);
然后您可以按如下方式遮盖椭圆下覆盖的位置:
Rectangle r=el.getBounds();
for(i=0; i<r.width; i++)
for(j=0; j<r.height; j++)
if(el.contains(r.x+i, r.y+j)) ... do whatever with this pixel add it to a list etc
--
对于像素 r.x+i、r.y+j,您可以获取 RGB 并从中获取各个字节:
int pixel=image.getRGB(r.x+i, r.y+j);
int red=(pixel&0x00ff0000)>>16, green=(pixel&0x0000ff00)>>8, blue=pixel&0x000000ff;
关于java - 从矩形构造椭圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41982911/