gpt4 book ai didi

Java:创建有孔的剪切区域?

转载 作者:搜寻专家 更新时间:2023-10-31 19:49:29 25 4
gpt4 key购买 nike

如何定义其中有孔的裁剪区域(通过 Graphics2D.clip(Shape))?

例如:一个矩形 r1 减去 r1 内的另一个矩形 r2

我确信这有一个简单的答案,但我正在画一个空白。

最佳答案

Path2D.append() + EVEN_ODD 缠绕规则似乎可以解决问题:

enter image description here

package com.example.test.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class HoleClipper extends JPanel
{
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Rectangle2D r1 = getBounds();
int margin = 50;
Rectangle2D r2 = new Rectangle2D.Double(
r1.getMinX()+margin,
r1.getMinY()+margin,
r1.getWidth()-2*margin,
r1.getHeight()-2*margin);

g2d.setColor(Color.YELLOW);
g2d.fill(r1);

Path2D p = new Path2D.Double(Path2D.WIND_EVEN_ODD);
p.append(r1, false);
p.append(r2, false);
g2d.clip(p);

int spacing = 10;
g2d.setColor(Color.BLACK);
for (double d = 0; d < r1.getWidth() + r1.getHeight(); d += spacing)
{
Line2D line = new Line2D.Double(0, d, d, 0);
g2d.draw(line);
}
}

public static void main(String[] args) {
HoleClipper clipper = new HoleClipper();
clipper.setPreferredSize(new Dimension(300, 200));

JFrame frame = new JFrame("HoleClipper");
frame.setContentPane(clipper);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

关于Java:创建有孔的剪切区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6280823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com