我正在尝试在 Graphics2D 渲染上创建 Punch Out 效果。
我有一个黑色的矩形。文本颜色为红色。我希望能够将颜色设置为 0x00FF0000 并将其从背景中“冲出”。
Graphics2D newG = (Graphics2D)g.create();
newG.setColor(new Color(0x00,0x00,0x00,0xFF)); //255 Alpha
newG.fillRect(box.x, box.y, box.width, box.height);
newG.setColor(new Color(0xFF,0x00,0x00,0x00)); //0 Alpha
newG.drawString("Welcome", box.x ,box.y);
我看到的是文本在背景下完全透明,但没有打洞。
我看到的:
我期望看到的内容:
如何使用 Graphics2D 实现“打洞”效果?
编辑:打洞效果就像使用前景设置为 0x00FF0000 和背景设置为 0xFF000000 的 JLabel。它从背景中“剪掉”/“打洞”文本。另外,我不希望它总是打出,只有当 alpha 为 0 时。
编辑2:我尝试了下面建议的代码,结果相同。
Rectangle stringBox = new Rectangle(x, y - fm.getHeight() + fm.getDescent(), fm.stringWidth(splitStr[i]), fm.getHeight());
TextLayout textLO = new TextLayout(splitStr[i], newG.getFont(), newG.getFontRenderContext());
Shape sText = textLO.getOutline(newG.getTransform()); // The Shape of text
Path2D.Double shape = new Path2D.Double(stringBox); // The rectangle
appendTextShape(shape, sText, newG.getTransform(), 0, 10);
newG.setColor(Color.black);
newG.fill(shape);
newG.setColor(new Color(0xFF, 0x00,0x00,0x00));
newG.drawString(splitStr[i], x, y);
最佳答案
http://docs.oracle.com/javase/tutorial/2d/advanced/compositing.html
正确设置构图是解决方案。 SRC_IN 是我正在寻找的作品。
关于java - 使用 Graphics2D 实现 "punch out"文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14385751/