1

我正在尝试使用swingx的 ShadowRenderer 为面板创建阴影。这是我到目前为止所做的:

  • 在面板构造函数中创建一次阴影渲染器。

    public CustomPanel() {
        super();
        renderer = new ShadowRenderer(20, 0.5f, Color.RED);
    }
    
  • 每次调整面板大小时,我都会重新计算新的阴影。

    @Override
    public void setBounds(int x, int y, int width, int height) {
        super.setBounds(x, y, width, height);
        shadow = renderer.createShadow(GraphicsUtilities.createCompatibleTranslucentImage(width, height));
    }
    
  • 然后我重写paintComponent面板的方法来绘制生成的图像:

    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g.create();
    
        g2.drawImage(shadow, 0, 0, null);
        //super.paintComponent(g);
    }
    

shadow图像从未显示。为什么?我读了这篇文章,除了我的代码来绘制一种由阴影渲染器生成的“阴影”图像。

4

1 回答 1

4

这是DropShadowDemo 的简短示例

JXPanel panel = new JXPanel() {
    int shadowSize = 40;
    ShadowRenderer renderer = new ShadowRenderer(shadowSize/ 2, 0.5f, Color.RED); 
    BufferedImage imageA = 
            XTestUtils.loadDefaultImage("moon.jpg");
    BufferedImage shadow;

    @Override
    public void setBounds(int x, int y, int width, int height) {
        super.setBounds(x, y, width, height);
        // not really needed here - the base image size is fixed
        shadow = renderer.createShadow(imageA); 
    }

    @Override
    protected void paintComponent(Graphics g) {
        int x = (getWidth() - imageA.getWidth()) / 2;
        int y = (getHeight() - imageA.getHeight()) / 2;

        Graphics2D g2 = (Graphics2D) g;
        Composite c = g2.getComposite();
        g2.setComposite(AlphaComposite.SrcOver.derive(renderer.getOpacity()));
        g.drawImage(shadow, x - shadowSize / 2, y - shadowSize / 2, null);
        g2.setComposite(c);
        g.drawImage(imageA, x, y, null);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(imageA.getWidth() + shadowSize, imageA.getHeight()+ shadowSize);
    }

};
panel.setOpaque(false);
于 2012-09-26T10:14:39.750 回答