【问题标题】:How to draw a sector of a BufferedImage?如何绘制 BufferedImage 的扇区?
【发布时间】:2016-02-15 04:15:14
【问题描述】:

我正在使用鼠标光标制作游戏,我想通过用绿色版本的图像覆盖光标来表示健康,但只有一个几何扇区对应于健康百分比。来自以下帖子的解决方案:Drawing slices of a circle in java? 和 How to draw portions of circles based on percentages in Graphics2D? 几乎是我想做的,但使用 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 的扇区?

【问题讨论】:

  • 您的弧线宽度为零,高度为零。它的 x 和 y 也为零。使用long constructor,它允许您设置它们(也使您不必使用显式三角函数)。

标签: java bufferedimage graphics2d


【解决方案1】:

如果您阅读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 Porter-Duff 模式在其上绘制图像。比如:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-22
    • 2022-01-09
    • 2014-02-07
    • 2011-10-08
    • 2011-09-07
    • 2017-11-02
    • 2014-11-20
    • 2016-08-03
    相关资源
    最近更新 更多