绘制出褪色的透明椭圆形

时间:2015-10-25 18:39:24

标签: java swing graphics

我正在尝试绘制一个渐弱的透明椭圆形以突出平铺屏幕上的瓷砖。不幸的是我无法在Swing中找到可以做到这一点的实现功能,所以我写了自己的:

private void drawGradientedOval(Graphics2D g2d, Rectangle bounds) {

    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    int loops = (int) Math.min(bounds.getWidth() / 2, bounds.getHeight() / 2);
    int x = bounds.x + (int) (bounds.getWidth() / 2);
    int y = bounds.y + (int) (bounds.getHeight() / 2);
    int scale = 1;
    float alpha = 0.5f;
    float step = alpha / loops;

    for (int i = 0; i < loops; i++) {
        g2d.setColor(new Color(1f, 1f, 1f, alpha));
        g2d.drawOval(x--, y--, scale, scale);
        scale += 2;
        alpha -= step;
    }

}

产生的椭圆形似乎(作物大于椭圆形边界):

enter image description here

结果不是光滑的椭圆形,有“十字架”和其他一些小文物。

我认为这是由相互重叠的“重叠”像素引起的。

有没有一种明智的解决方法?

请注意,我宁愿避免实施较低级别的解决方案,例如在Raster级别操纵单个像素,因为这种努力涉及上面未提及的大量变量。

1 个答案:

答案 0 :(得分:4)

为什么不使用RadialGradientPaint对象来进行绘画?类似的东西:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RadialGradientPaint;
import javax.swing.*;

@SuppressWarnings("serial")
public class GradOval extends JPanel {
    private static final int PREF_W = 400;
    private static final int PREF_H = PREF_W;
    private static final Color BG = Color.BLACK;
    private static final float[] FRACTIONS = {0.0f, 1.0f};
    private static final Color[] COLORS = {Color.LIGHT_GRAY, new Color(0, 0, 0, 0)};

    public GradOval() {
        setBackground(BG);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        float cx = getWidth() / 2f;
        float cy = getHeight() / 2f;
        float radius = cx;       
        Paint paint = new RadialGradientPaint(cy, cy, radius, FRACTIONS, COLORS);
        Graphics2D g2 = (Graphics2D) g;
        g2.setPaint(paint);
        g2.fillRect(0, 0, getWidth(), getHeight());        
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private static void createAndShowGui() {
        GradOval mainPanel = new GradOval();

        JFrame frame = new JFrame("GradOval");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

这将显示为:

enter image description here