我正在努力实现以下目标
http://www.qksnap.com/i/3hunq/4ld0v/screenshot.png
我目前能够使用以下代码在半透明玻璃板背景上成功绘制矩形:
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g.setColor(Color.black); // black background
g.fillRect(0, 0, frame.getWidth(), frame.getHeight());
g2.setColor(Color.GREEN.darker());
if (getRect() != null && isDrawing()) {
g2.draw(getRect()); // draw our rectangle (simple Rectangle class)
}
g2.dispose();
}
哪个效果很好,但是,我希望矩形内的区域完全透明,而外部仍然变暗,就像上面的截图一样。
有什么想法吗?
答案 0 :(得分:5)
..矩形内的区域是完全透明的,而外部仍然像上面的截图一样变暗。
Rectangle
(componentRect
),其大小与正在绘制的组件的大小相同。Area
(componentArea
)(new Area(componentRect)
)。Area
。{/ li>的selectionArea
(selectionRectangle
)
componentArea.subtract(selectionArea)
以删除所选部分。Graphics.setClip(componentArea)
答案 1 :(得分:5)
正如安德鲁建议的那样(在我结束我的榜样时,只是打败了我)
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g.setColor(Color.black); // black background
Area area = new Area();
// This is the area that will filled...
area.add(new Area(new Rectangle2D.Float(0, 0, getWidth(), getHeight())));
g2.setColor(Color.GREEN.darker());
int width = getWidth() - 1;
int height = getHeight() - 1;
int openWidth = 200;
int openHeight = 200;
int x = (width - openWidth) / 2;
int y = (height - openHeight) / 2;
// This is the area that will be uneffected
area.subtract(new Area(new Rectangle2D.Float(x, y, openWidth, openHeight)));
// Set up a AlphaComposite
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
g2.fill(area);
g2.dispose();
}