移动一个具有渐变填充的矩形

时间:2015-07-04 00:39:30

标签: java graphics awt gradient graphics2d

当我使用矩形的(0,0)“矩形(0,0,100,100)”的坐标时,我得到渐变。当我使用时:

GradientPaint gp = new GradientPaint(0, 0, c1, 0, 100, c2);
Rectangle reckt = new Rectangle(0,100,100,200);

渐变消失。我做错了什么?

 public void draw( Graphics g ) {
    Graphics2D g2d = (Graphics2D) g;

    c1 = new Color(0, 0, 255);
    c2 = new Color(0, 255, 255);
    GradientPaint gp = new GradientPaint(0, 0, c1, 0, 100, c2);

    g2d.setPaint(gp);
    Rectangle reckt = new Rectangle(0,0,100,100);
    g2d.fill(reckt);

}

1 个答案:

答案 0 :(得分:1)

前两个参数定义渐变开始的x / y点,第四个和第五个定义高度和宽度。所以基本上,你要在渐变填充之外绘制矩形

您有两个选项,要么GradientFill更改x / y位置,要么使用AffineTransformtranslate Graphics上下文来更改您要绘制的位置

总是在0x0处绘制

AffineTransform允许您翻译(除其他外)Graphics上/左位置,例如......

Translated

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestTranslate {

    public static void main(String[] args) {
        new TestTranslate();
    }

    public TestTranslate() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Color c1 = new Color(0, 0, 255);
            Color c2 = new Color(0, 255, 255);
            GradientPaint gp = new GradientPaint(0, 0, c1, 0, 100, c2);
            for (int offset = 0; offset < getWidth(); offset += 50) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setPaint(gp);
                g2d.setTransform(AffineTransform.getTranslateInstance(offset, offset));
                g2d.fill(new Rectangle(0, 0, 100, 100));
                g2d.dispose();
            }
        }

    }

}