gpt4 book ai didi

java - 将 Shape 的中心与 JPanel 的中心对齐

转载 作者:行者123 更新时间:2023-12-02 08:52:48 26 4
gpt4 key购买 nike

我一直在尝试将 java2d 形状的中心与 JPanel 的中心对齐,但没有成功。我可以使用 getBounds 方法对图像和许多二维形状(如平行四边形)执行此操作,但不能对菱形执行此操作,尽管它们都遵循相同的模式。严重的是,当我从实际项目中准备 SSCCE 时,我无法正确对齐它们。我编写了一个用于在中心绘制形状的drawShape方法。我不明白我哪里错了。这是SSCCE:

            import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class TestPanel extends JPanel{
Point a,b,c,d;
Shape trapezium,parallelogram;
Random random=new Random();
public TestPanel(){
a=new Point();
b=new Point();
c=new Point();
d=new Point();
rhombusFactory(a,b,c,d);
trapezium=getQuadrilateral(a,b,c,d);


}
private void rhombusFactory(Point a,Point b,Point c,Point d)
{ int width=random.nextInt(200-100)+100;
int height=random.nextInt(150-50)+50;
a.x=0;
a.y=0;
b.x=a.x+width/2;
b.y=a.y+height/2;
c.x=a.x+width;
c.y=a.y;
d.x=a.x+width/2;
d.y=a.y-height/2;
}
private void parallelogramFactory(Point a,Point b,Point c,Point d){
int l1=random.nextInt(200-100)+100;
int l2=random.nextInt(150-70)+70;
int offset=(random.nextInt(2)==0?-1:1)*(random.nextInt(50-20)+20);
a.x=0;
a.y=0;
b.x=a.x+l1;
b.y=a.y;
d.x=a.x+offset;
d.y=a.y+l2;
c.x=d.x+l1;
c.y=d.y;
}
private Shape getQuadrilateral(Point a,Point b,Point c,Point d){
GeneralPath gp=new GeneralPath();
gp.moveTo(a.x,a.y);
gp.lineTo(b.x,b.y);
gp.lineTo(c.x,c.y);
gp.lineTo(d.x,d.y);
gp.closePath();
return gp;
}
private void drawShape(Graphics2D g,Shape shape){
AffineTransform oldt=g.getTransform();
Rectangle2D bounds=shape.getBounds2D();
double height=bounds.getHeight();
double width=bounds.getWidth();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
g.translate(this.getWidth()/2,this.getHeight()/2);
g.translate(-width/2,-height/2);
g.draw(shape.getBounds2D());
g.draw(shape);
g.setTransform(oldt);
}
public void paintComponent(Graphics g2){
super.paintComponent(g2);
Graphics2D g=(Graphics2D)g2;
drawShape(g,trapezium);
//drawShape(g,parallelogram);
}
public static void main(String args[]){
JFrame jf=new JFrame();
TestPanel tp=new TestPanel();
jf.setLayout(new BorderLayout());
jf.add(tp,BorderLayout.CENTER);
jf.setSize(500,500);
jf.setVisible(true);
}
}

如有任何帮助,我们将不胜感激编辑:我刚刚从代码中删除了令人困惑的行...

最佳答案

您需要考虑形状的有界 x/y 位置:

Rectangle bounds=shape.getBounds(); // changed this
...
//g.translate(this.getWidth()/2,this.getHeight()/2);
//g.translate(-width/2,-height/2);
g.translate((this.getWidth() - width) / 2,(this.getHeight() - height) / 2);
g.translate(-bounds.x, -bounds.y); // added this

关于java - 将 Shape 的中心与 JPanel 的中心对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16637633/

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