简体   繁体   English

渐变色填充| 爪哇| 图形类

[英]Gradient Color Fill | Java | Graphics Class

How can I fill this rectangle with a gradient?如何用渐变填充这个矩形?

I've seen many examples of how to do this, but I've tried and for some reason, I can't seem to get it.我已经看过很多关于如何做到这一点的例子,但我已经尝试过,但出于某种原因,我似乎无法理解。

If somebody could help me start that would be greatly appreciated.如果有人可以帮助我开始,将不胜感激。

This is my code, I'm using the Drawing Panel.这是我的代码,我正在使用绘图面板。

import java.awt.*;
public class Gradient {
    public static void main(String[] args) {
        
        DrawingPanel dp = new DrawingPanel(700,900);
        Graphics g = dp.getGraphics();
        
        g.fillRect(20, 20, 100, 150);
    }
}

You should start with Painting in AWT and Swing and Performing Custom Painting to get a better understanding how painting in Swing works (hint getGraphics isn't it)您应该从AWT 中的绘画和 Swing执行自定义绘画开始,以更好地了解 Swing 中的绘画是如何工作的(提示getGraphics不是)

You should then take a look at 2D Graphics and Stroking and Filling Graphics Primitives然后你应该看看2D Graphics and Stroking and Filling Graphics Primitives

在此处输入图片说明

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 javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {

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

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                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);
            Graphics2D g2d = (Graphics2D) g.create();
            Color c1 = new Color(0, 0, 255);
            Color c2 = new Color(0, 255, 255);
            GradientPaint gp = new GradientPaint(0, 0, c1, 0, getHeight(), c2);
            g2d.setPaint(gp);
            g2d.fillRect(0, 0, getWidth(), getHeight());
            g2d.dispose();
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM