每次调用paintComponent()时,Graphics2D是否会重置合成?又为什么呢

例如,

public void paintComponent(Graphics g)

    {
    Graphics2D g2 = (Graphics2D)g;
    System.out.println(((AlphaComposite)g2.getComposite()).getAlpha()); //printing alpha value before setting composition
    g.drawImage(background,0,0,500,500,null);
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
    g.setColor(Color.RED);
    g.fillOval(x-100,y-100,200,200);
    System.out.println(((AlphaComposite)g2.getComposite()).getAlpha()); //printing alpha value after setting composition
}


当paintComponent()被多次调用时,以上代码将输出以下内容...

1.0

0.5

1.0

0.5

1.0

0.5

1.0

0.5

这是否意味着graphics2D在paintComponent()之后重置了合成,为什么必须这样做?

最佳答案

是;您的结果就是预期的结果。在Default Rendering Attributes中,默认组合
应用AlphaComposite.SRC_OVER规则,该规则“等效于setComposite(new AlphaComposite.SrcOver)”。请注意,AlphaComposite.SrcOver的alpha值为1.0f

07-27 19:57