gpt4 book ai didi

Java Swing : drawLine very slow

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:55:20 26 4
gpt4 key购买 nike

我正在使用 swing 编写一个 java 应用程序,我需要在其中在正方形上方绘制一个网格。为此,我使用了 Graphics 类提供的 drawLine(...) 方法。

除了绘制每条线需要花费大量时间(50 条线超过 20 秒...)外,一切正常。我什至可以看到实时绘制的线条。一件奇怪的事情是水平线的绘制速度比垂直线快得多(几乎是瞬间)。

我可能做错了什么。这是网格的代码。

public void drawGrid(Graphics g){
g.setColor(new Color(255, 255, 255, 20));
int width = getWidth();
int height = (int) (width * Utils.PLATE_RATIO);
int step = pixelSize*gridSpacing;
Color bright = new Color(255, 255, 255, 100);
Color transparent = new Color(255, 255, 255, 20);
for(int ix = insets.left + step;
ix < width; ix += step){
if(((ix - insets.left) / step) % 10 == 0){
g.setColor(bright);
}
else{
g.setColor(transparent);
}
g.drawLine(ix, insets.top, ix, height+insets.top);
}
for(int iy = insets.top+step;
iy < (insets.top + height); iy += step){
if(((iy - insets.top) / step) % 10 == 0){
g.setColor(bright);
}
else{
g.setColor(transparent);
}
g.drawLine(insets.left, iy, width + insets.left, iy);
}
}

最佳答案

你发的代码没问题,没有问题。
这是一个使用您的方法的组件的工作示例(有点简化):

public static class MyGrid extends JComponent
{
private int step = 10;

public MyGrid ()
{
super ();
}

public Dimension getPreferredSize ()
{
return new Dimension ( 500, 500 );
}

protected void paintComponent ( Graphics g )
{
super.paintComponent ( g );
drawGrid ( g );
}

public void drawGrid ( Graphics g )
{
int width = getWidth ();
int height = getHeight ();
Color bright = new Color ( 255, 255, 255, 200 );
Color transparent = new Color ( 255, 255, 255, 100 );

for ( int ix = step; ix < width; ix += step )
{
if ( ( ix / step ) % 10 == 0 )
{
g.setColor ( bright );
}
else
{
g.setColor ( transparent );
}
g.drawLine ( ix, 0, ix, height );
}

for ( int iy = step; iy < height; iy += step )
{
if ( ( iy / step ) % 10 == 0 )
{
g.setColor ( bright );
}
else
{
g.setColor ( transparent );
}
g.drawLine ( 0, iy, width, iy );
}
}
}

我猜那段代码之外有一些问题。

附言有点题外话但是...

我建议您计算绘制区域的可见部分(使用 JComponent 的 getVisibleRect() 方法或 Graphics g.getClip().getBounds() 方法)并将您的绘画限制在该区域。

如果组件非常大(例如组件区域为 10000x10000 像素),那么这个小的优化可以及时加快组件的绘制。

关于Java Swing : drawLine very slow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13043865/

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