Java awt/swing AffineTransformation 在形状周围移动
一旦一次绘制了数百个圆圈,一个动画圆圈的程序就无法流畅地绘制它们。建议使用仿射变换来复制形状。这段代码被重构为使用graphics2D,可以工作,但不会导致任何性能提升,因为它仍然填充数百个椭圆。如何正确使用仿射变换来填充形状一次,然后复制/移动它?
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.WHITE);
for (int i = 0; i < gameLogic.getParticleArrSize(); i++) {
Graphics2D g2 = (Graphics2D) g;
Color color = new Color(6,6,6);
Ellipse2D oval = new Ellipse2D.Double(
gameLogic.getParticleXCoor(i),
gameLogic.getParticleYCoor(i),
gameLogic.getParticleSize(i),
gameLogic.getParticleSize(i));
g2.setPaint(color);
g2.fill(oval);
g2.translate(15, 15);
g2.fill(oval);
}
}
A program that animates circles is not drawing them fluidly once several hundred are drawn at once. It was suggested to use affine transformation to copy the shapes. This code, refactored to use graphics2D, works, but doesn't cause any performance boost since it is still filling hundreds of ovals. How to use affinetransformation properly to fill a shape once and then copy/move it?
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.WHITE);
for (int i = 0; i < gameLogic.getParticleArrSize(); i++) {
Graphics2D g2 = (Graphics2D) g;
Color color = new Color(6,6,6);
Ellipse2D oval = new Ellipse2D.Double(
gameLogic.getParticleXCoor(i),
gameLogic.getParticleYCoor(i),
gameLogic.getParticleSize(i),
gameLogic.getParticleSize(i));
g2.setPaint(color);
g2.fill(oval);
g2.translate(15, 15);
g2.fill(oval);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
知道哪个更快的唯一方法是分析两个或多个实现。作为一个具体示例,此动力学模型显示了梯度的轻微优势 em> 模式,使用
drawImage()
,在 Color 模式下,使用fill()
,如paintComponent()
DisplayPanel
方法。在这种情况下,AffineTransform
有利于预渲染更复杂的渐变图像。附录:
我怀疑
AffineTransform
是解决方法。相反,将对象创建移出循环,如 @camickr 建议的那样。在示例中,请注意Ensemble
仅需要一个 <代码>Ellipse2D;它重复使用setFrame()
。此外,每个粒子
已经知道它的颜色
。最后,观察示例如何测量绘制时间。The only way to know which is faster is to profile two or more implementations. As a concrete example, this kinetic model shows a slight advantage for Gradient mode, using
drawImage()
, over Color mode, usingfill()
, as seen in thepaintComponent()
method ofDisplayPanel
. In this context,AffineTransform
is beneficial in pre-rendering the more complex gradient image.Addendum:
I doubt that
AffineTransform
is the cure. Instead, move the object creation out of the loop, as @camickr suggests. In the example, note how anEnsemble
only needs oneEllipse2D
; it usessetFrame()
repeatedly. Also, eachParticle
already knows itsColor
. Finally, observe how the example measures paint time.怀疑这会产生很大的差异,但是:
我还见过一个使用 5000 个球没有问题的例子。它使用 fillOval(...) 方法。不知道这是否会有所作为。
Doubt it will make a big difference but:
I've also seen an example that uses 5000 balls without a problem. It uses the fillOval(...) method. Don't know if that will make a difference.