我试图在中间划清界线.我尝试了不同的坐标 [英] I am trying to draw the line in the middle. I tried different coordinates

查看:88
本文介绍了我试图在中间划清界线.我尝试了不同的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的paintComponent,其中包含坐标

Here is my paintComponent which contains the coordinates

public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g; 
        g2.drawLine(-100,0,500,0);
        g2.drawLine(141,-500,141,500);
        g2.translate(getWidth()/2.0, getHeight()/2.0);
        g2.scale(1,-1);
        g2.rotate(45*Math.PI/180);
        Rectangle2D r = new Rectangle2D.Double(0,0,100,100);
        g2.fill(r);

推荐答案

有点作弊,但是...

It's a bit of a cheat, but...

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g.create();
    g2.drawLine(getWidth() / 2, 0, getWidth() / 2, getHeight());
    g2.drawLine(0, getHeight() / 2, getWidth(), getHeight()/ 2);
    g2.translate(getWidth() / 2.0, (getHeight() / 2.0));
    g2.scale(1, -1);
    g2.rotate(45 * Math.PI / 180);
    Rectangle2D r = new Rectangle2D.Double(-50, -50, 100, 100);
    g2.fill(r);
    g2.dispose();
}

基本上,原点现在是屏幕的中心,因此要绘制围绕原点居中"的矩形,您需要相应地调整x/y.

Basically, the origin point is now the center of the screen, so in order to draw the rectangle "centered" around the origin point, you need to adjust the x/y accordingly

现在,您也可以通过50x50调整原点,但是随后您需要更改将Graphics上下文围绕其旋转到框中心的锚点

Now, you also adjust the origin point by 50x50 instead, but then you'd need to change the anchor point around which the Graphics context is rotated to the center of the box

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g.create();
    g2.drawLine(getWidth() / 2, 0, getWidth() / 2, getHeight());
    g2.drawLine(0, getHeight() / 2, getWidth(), getHeight()/ 2);
    g2.translate((getWidth() / 2.0) - 50, (getHeight() / 2.0) - 50);
    g2.scale(1, -1);
    g2.rotate(45 * Math.PI / 180, 50, 50);
    Rectangle2D r = new Rectangle2D.Double(0, 0, 100, 100);
    g2.fill(r);
    g2.dispose();
}

这篇关于我试图在中间划清界线.我尝试了不同的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆