我想在圆圈上写一个文字。文本和圆的交叉区域必须是不同的颜色。
起初我想使用区域类,但我无法弄清楚如何将文本转换为区域。
我仍然不知道如何将文本转换为形状或其他内容。
以下是示例图片:
void paintComponent(Graphics g){
Ellipse2D myEllipse = new Ellipse2D.Double(20,20,100,100);
//i have no idea how to create a text as a shape.
//if i was able to create a text as a shape,i would name it "myText"
a1.add(new Area(myEllipse));
a2.add(new Area(myText));
g2.setColor(Color.red);
g2.fill(myEllipse);
g2.setColor(Color.CYAN);
g2.fill(myText);
a1.intersect(a2);
g2.setColor(Color.BLACK);
g2.fill(a1);
}
答案 0 :(得分:4)
绘画引擎可以自己处理。看看XOR-Mode for Graphics:
http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html#setXORMode(java.awt.Color)
在您的示例中,您必须在写入文本之前将XOR颜色设置为白色:
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.white);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.setColor(Color.BLUE);
g2.fill(myEllipse);
g2.setColor(Color.red);
g2.setXORMode(Color.white); // Set XOR mode to white
g2.drawString(myText, 70, 70);
找到正确的XOR颜色可能非常棘手。但是对于this question,你必须对图形的前景,XOR颜色和你要绘制的颜色进行按位异或。
对于我们得到的圆圈区域:
Foreground = FF 00 00 (red)
XOR-Color = FF FF FF (white)
Background = 00 00 FF (blue)
----------------------
Result = 00 FF 00 (green)
和外面:
Foreground = FF 00 00 (red)
XOR-Color = FF FF FF (white)
Background = FF FF FF (white)
----------------------
Result = FF 00 00 (red)
<强>更新强>
要查找XOR /前景对,您可以执行以下操作:
您必须通过XOR将背景和结果颜色组合在一起。我们看到,对于这两种情况(在椭圆和外部),我们都有
Ellispe: 00 00 FF ^ 00 FF 00 = 00 FF FF
Outside: FF FF FF ^ FF 00 00 = 00 FF FF
因此,我们可以选择XOR导致00 FF FF
的任何XOR /前景对。在这个例子中,我使用白色和红色,但黑色和青色会产生相同的结果。
答案 1 :(得分:3)
绘制圆圈和绘制文字相当简单。感谢{2}用于Graphics2D方法更改圆圈中文本的颜色。
这是代码。
package com.ggl.testing;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SimplePainting implements Runnable {
@Override
public void run() {
JFrame frame = new JFrame("Simple Painting");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PaintPanel paintPanel = new PaintPanel();
frame.add(paintPanel);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new SimplePainting());
}
class PaintPanel extends JPanel {
private static final long serialVersionUID =
-5950526117015270963L;
private Ellipse2D myEllipse =
new Ellipse2D.Double(20, 20, 100, 100);
private String myText = "Testing, one, two, three";
public PaintPanel() {
this.setPreferredSize(new Dimension(400, 200));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setXORMode(Color.WHITE);
g2d.setColor(Color.RED);
g2d.fill(myEllipse);
g2d.setColor(Color.CYAN);
g2d.drawString(myText, 70, 70);
}
}
}