内部与Java图形剪辑 [英] Inside clipping with Java Graphics
本文介绍了内部与Java图形剪辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用java.awt.Graphics绘制一条线,但只有位于矩形外部的线的部分应该呈现。
I need to draw a line using java.awt.Graphics, but only the portion of the line that lies outside of a rectangle should be rendered.
是吗?可能使用图形剪辑支持还是我需要计算交叉点并剪切线自己?
Is it possible to use the Graphics clipping support or do I need to calculate the intersection and clip the line myself?
推荐答案
您需要使用区域课程。这个例子将演示如何去做你所要求的:
You need to use the Area class. This example will demonstrate how to do what you ask:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Area;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test extends JPanel {
public static void main(String[] args) {
JFrame f = new JFrame();
Test t = new Test();
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(t,BorderLayout.CENTER);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public Test() {
setPreferredSize(new Dimension(300, 300));
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g.create();
Rectangle2D rectangleNotToDrawIn = new Rectangle2D.Double(100, 100, 20, 30);
Area outside = calculateRectOutside(rectangleNotToDrawIn);
g2.setPaint(Color.white);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.setPaint(Color.black);
g2.setClip(outside);
g2.drawLine(0, 0, getWidth(), getHeight());
}
private Area calculateRectOutside(Rectangle2D r) {
Area outside = new Area(new Rectangle2D.Double(0, 0, getWidth(), getHeight()));
outside.subtract(new Area(r));
return outside;
}
}
这篇关于内部与Java图形剪辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文