簡體   English   中英

如何繪制多邊形,然后按比例調整大小並將其移動到顯示區域的中心?

[英]How to draw a polygon, then resize it by scale and move it to center of display area?

我在Graphics2d和Polygon上做作業,但是我無法搜索(或者使用錯誤的關鍵字?)我的作業解決方案。

Hoemwork問題截圖:

IMG

下面的代碼是我嘗試的第一種方法,我只看到空屏幕。 在谷歌搜索后,我意識到我錯誤地使用.scale和.translate,所以我在.drawPolygon之前移動它,這次我可以看到多邊形,但它是在我放大窗口之后,這意味着它不是最初在300,300內可見?

import javax.swing.*;
public class PolygonExample extends JFrame{
    public PolygonExample(){
        super("Drawing Red Polygon");
        setSize(300, 300);
        setVisible (true);
    }
    public void paint (Graphics g){
        super.paint(g);
        int xValue[] = {0, 10, 7, -7, -10};
        int yValue[] = {-10, -2, 10, 10, -2};
        Polygon polygon = new Polygon(xValue, yValue, 5);
        g.setColor(Color.RED);
        g.drawPolygon(polygon);

        Graphics2D g2d = (Graphics2D) g;
        g2d.scale(5.0, 5.0);
        g2d.translate(150, 150);
    }
    public static void main(String[] args) {
        new PolygonExample();
    }
}

我希望多邊形將繪制在顯示區域的中心(300x300以內),但我沒有在屏幕上看到任何內容。 放大窗口后,我可以看到我的多邊形,但它不在我設置的300,300區域內

import javax.swing.*;
import java.awt.geom.AffineTransform;
public class PolygonExample extends JFrame{
    public PolygonExample(){
        super("Drawing Red Polygon");
        setSize(300, 300);
        setVisible (true);
    }
    public void paint (Graphics g){
        super.paint(g);
        int xValue[] = {0, 10, 7, -7, -10};
        int yValue[] = {-10, -2, 10, 10, -2};
        Polygon polygon = new Polygon(xValue, yValue, 5);

        g.setColor(Color.RED);
        Graphics2D g2d = (Graphics2D) g;
        AffineTransform at = new AffineTransform(5., 0., 0., 5., 150., 150.);
        g2d.setTransform(at);

        g.drawPolygon(polygon);     
    }
    public static void main(String[] args) {
        new PolygonExample();
    }
}

上面的代碼完成了我想做的事情

感謝@MadProgrammer的資源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM