【发布时间】:2017-02-01 15:00:31
【问题描述】:
我正在制作一个有点像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);
}
}
}
如果有什么方法可以让我的问题更清楚,请告诉我。
【问题讨论】:
标签: java image-processing shapes ellipse