gpt4 book ai didi

java - 在 JAVA 中使用 RadialGradientPaint 创建光

转载 作者:行者123 更新时间:2023-12-02 11:06:54 24 4
gpt4 key购买 nike

我正在使用 java 开发一个简单的游戏引擎。我想在游戏中添加一些光线,并且我想使用 RadialGradientPaint。

这是我的轻量级

package engine.graphics;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RadialGradientPaint;
import java.awt.geom.Point2D;

import engine.Main;
import engine.maths.Vector2f;

public class Light
{
private Vector2f pos;
private int radius;

public Light(Vector2f pos, int radius)
{
this.pos = pos;
this.radius = radius;
}

public void render(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
Point2D center = new Point2D.Float(pos.x, pos.y);
float[] dist = {0.9f, 1.0f};
Color[] color = {new Color(0.0f, 0.0f, 0.0f, 0.1f), new Color(0, 0, 0, 255)};
RadialGradientPaint p = new RadialGradientPaint(center, radius, dist, color);
g2d.setPaint(p);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .95f));
g2d.fillRect(0, 0, Main.WIDTH, Main.HEIGHT);
g2d.dispose();
}
}

我发现的问题是我无法绘制多于一盏灯。我怎样才能修改我的代码来制作更多的灯?谢谢..

最佳答案

我向你建议:

package solamda;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RadialGradientPaint;
import java.awt.geom.Point2D;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
private static final Color transparency = new Color(0, 0, 0, 0);
private static final int WIDTH = 500;
private static final int HEIGHT = 500;

public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setMinimumSize(new Dimension(WIDTH, HEIGHT));
f.setLayout(new BorderLayout());
f.add(new JLabel() {
@Override
public void paint(Graphics g) {
super.paint(g);
render(g);
}
});

f.pack();
f.setVisible(true);
}

public static void render(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Point[] lights = { new Point(WIDTH / 2, HEIGHT / 2), new Point(0,0),
new Point(WIDTH / 2+10, HEIGHT / 2), new Point(WIDTH / 2-10, HEIGHT / 2) };
for (Point center : lights) {
paintlight(g2d, center);
}
g2d.dispose();
}

private static void paintlight(Graphics2D g2d, Point center) {
float[] dist = { 0.2f, 1.0f };
Color[] color = { Color.white, transparency };
RadialGradientPaint p = new RadialGradientPaint(center, 10, dist, color);
g2d.setPaint(p);
g2d.fillRect(center.x - 20, center.y - 20, 40, 40);

}
}

您不需要仅填充整个矩形,仅填充光线所在的部分。因此,从您的代码中,我只需提取一个方法,其中 center 是一个参数(调用 Paintlight),然后在您的方法渲染中,我可以绘制任意数量的灯光;我只是在这一点周围画了一个白色的hello,并且在画它时保持了图案的透明度

关于java - 在 JAVA 中使用 RadialGradientPaint 创建光,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50887719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com