使用Graphics2D的scale()
函数时,如果使用两个不同的参数(在x和y方向上按不同比例缩放),之后绘制到此Graphics2D对象上的所有内容都会被缩放。这会产生一种奇怪的效果,沿一个方向绘制的线条比沿另一个方向绘制的线条更粗。下面的程序演示了这种效果,并显示了该窗口:
public class StrokeExample extends JPanel {
public void paintComponent(Graphics context) {
super.paintComponent(context);
Graphics2D g = (Graphics2D)context.create();
g.setStroke(new BasicStroke(0.2f));
int height = getHeight();
int width = getWidth();
g.scale(width/7.0, height/4.0);
g.setColor(Color.BLACK);
g.draw(new Rectangle( 2, 1, 4, 2));
}
public static void main(String[] params) {
EventQueue.invokeLater(new Runnable(){public void run() {
StrokeExample example = new StrokeExample();
JFrame f = new JFrame("StrokeExample");
f.setSize(100, 300);
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(example);
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.setVisible(true);
}});
}
}
我正在使用这个坐标转换来避免手动将我的应用程序模型坐标(在此示例中为(2,1, 2,4))转换为屏幕(或组件)像素坐标,但是我不想有这种笔画扭曲效果。换句话说,我希望所有的线条宽度都相同,与当前的x和y缩放因子无关。
我知道产生这种效果的原因(Stoke对象在用户坐标系中创建一个要绘制的矩形的描边形状,然后将其转换为屏幕坐标),但我不确定如何解决这个问题。
- 我应该创建一个新的描边实现,在X和Y方向上以不同的方式描绘形状(从而撤消此处的扭曲)?(或者是否已经有人知道这样的实现?)
- 我应该将我的形状转换为屏幕坐标并在那里作描边吗?
- 还有其他更好的想法吗?