在摆动中设置渐变方向

时间:2014-04-21 20:28:09

标签: java swing awt java-2d

我一直试图在秋千中绘制线条并使用渐变来获得类似激光的效果。我想在线条的宽度上应用渐变(例如:红线核心渐变为边缘的橙色)。问题是当我以某个角度绘制时,我想以某种方式将相同的角度应用于渐变。

public void paintComponent(Graphics g) {
        Graphics2D en = (Graphics2D) g;
        GradientPaint gp = new GradientPaint(25, 25, Color.red, 15, 25,
                Color.orange, true);
        en.setPaint(gp);
        en.setStroke(new BasicStroke(4.0F));
        en.drawLine(10, 10, 800, 600);
}

1 个答案:

答案 0 :(得分:3)

一个简单的诀窍就是在Graphics2D上调用setTransform()。这将为您同时旋转线条和渐变。如果你不想这样做,那么你必须自己旋转渐变(所以基本上是手动的渐变的pt1和pt2,即你需要根据你应用到你的线上的旋转来计算它们)

这是一个说明我的第一个想法的小例子。只需在底部滑动自动收报机,即可观看围绕面板中心旋转的线条(和渐变):

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class TestPanel extends JPanel {

    private double angle = 0;

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D en = (Graphics2D) g;
        AffineTransform tf = AffineTransform.getTranslateInstance(-getWidth() / 2, -getHeight() / 2);
        tf.preConcatenate(AffineTransform.getRotateInstance(Math.toRadians(angle)));
        tf.preConcatenate(AffineTransform.getTranslateInstance(getWidth() / 2, getHeight() / 2));
        en.setTransform(tf);
        GradientPaint gp = new GradientPaint(25, 25, Color.red, 15, 25, Color.orange, true);
        en.setPaint(gp);
        en.setStroke(new BasicStroke(4.0F));
        en.drawLine(400, 400, 600, 600);
    }

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

    public void setAngle(double angle) {
        this.angle = angle;
        repaint();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                final TestPanel panel = new TestPanel();
                final JSlider slider = new JSlider(0, 360);
                slider.addChangeListener(new ChangeListener() {

                    @Override
                    public void stateChanged(ChangeEvent e) {
                        panel.setAngle(slider.getValue());
                    }
                });
                slider.setValue(0);
                frame.add(panel);
                frame.add(slider, BorderLayout.SOUTH);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}