2016-02-14 103 views
0

我正在用鼠標光標進行遊戲,我想通過將光標與圖像的綠色版本疊加來表示健康狀況,但只有與健康百分比對應的幾何扇區。像這些帖子的解決方案:Drawing slices of a circle in java? & How to draw portions of circles based on percentages in Graphics2D?幾乎是我想要做的,但與一個BufferedImage,而不是一個純色填充。如何繪製一個BufferedImage的扇區?

//Unfortunately all this does is cause nothing to draw, but commenting this out allows the overlay image to draw 
    Arc2D.Double clip = new Arc2D.Double(Arc2D.PIE); 
    double healthAngle = Math.toRadians((((Double)data.get("health")).doubleValue() * 360.0/100.0) - 270.0); 
    clip.setAngles(0, -1, Math.cos(healthAngle), Math.sin(healthAngle)); 
    System.out.println(Math.cos(healthAngle) + " " + Math.sin(healthAngle)); 
    g.setClip(clip); 

總之,如何繪製一個給定角度的BufferedImage的扇區?

+1

您的弧具有零寬度和零高度。它的x和y也是零。使用[long構造函數](https://docs.oracle.com/javase/8/docs/api/java/awt/geom/Arc2D.Double.html#Double-double-double-double-double-double-double -int-),它允許你設置它們(也可以避免使用明確的三角)。 – VGR

回答

0

如果您閱讀setClip(Shape)的API文檔,您會看到唯一能夠保證工作的形狀是矩形。所以,設置剪輯可能不起作用。

但是,還有其他選擇。最明顯的可能是使用TexturePaint來填充你的弧線BufferedImage。類似:

TexturePaint healthTexture = new TexturePaint(healthImg, new Rectangle(x, y, w, h)); 
g.setPaint(healthTexture); 
g.fill(arc); // "arc" is same as you used for "clip" above 

另一個選項是第一畫圓弧在純色,在透明的背景,然後繪製圖像上,當使用該SRC_IN波特 - 達夫模式。例如:

g.setPaint(Color.WHITE); 
g.fill(arc); // arc is same as your clip 
g.setComposite(AlphaComposite.SrcIn); // (default is SrcOver) 
g.drawImage(x, y, healthImg, null);